This is a test version of Biostars. For the public version, visit https://www.biostars.org.
R for loop trouble with paste0 an variable assignment

Hi,

I'm trying to loop through a string vector called iter in order to subset a data frame in R. I would like to filter that data frame using i iter value in the loop and assign it to a variable using iter value i. however, it wasnt working I think variable assignment is not properly done.

 for ( i in iter) {
      paste0(i)<-subset(out,TestId==paste0(i) & AddId=="Curve_F_Cor")
    }

I have tried with assign built in R function but i havent and seems to work

for ( i in iter) {
  assign(i, subset(out,TestId==paste0(i) & AddId=="Curva_F_Cor"))
}

I have read several times that using assign in this way is not very nice. I've read about lapply but i cannot figure out how to use it Which one would be the best option to do it?

Thanks

r for paste0

Hi Neuls,

I have modified your post using code formatting for better readability, by selecting the code and clicking the 101010 button. Please keep this option in mind for next time!

This is not exactly a bioinformatics question (more closely just R programming) so this might get closed for that reason, although you probably get this issue when trying to solve a bioinformatics issue...

Cheers,
Wouter

I highly suggest to read some introduction to R. You can find several tutorials in the web. Couple of points:

  • No need to use loops in R to subset variables.
  • paste0 is a function. If you are using it as a variable name that might cause trouble.
  • In R you subset using [, so paste0(i) is wrong.

If you have a data.frame d in R with a row named "A", you can do d["A", ] and will give you that row. If instead you want the row in which column "C" is equal to, say, some value i, then you would do d["C" == i, ] and that will give you the rows satisfying the condition.

Hello Neuls!

We believe that this post does not fit the main topic of this site.

Not a bioinformatics question. You need to consult R documentation on subsetting dataframes, there is no need to use for loops, instead you can subset the data directly with the string vector.

For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.

If you disagree please tell us why in a reply below, we'll be happy to talk about it.

Cheers!

0 answers

No answers yet.

Log in to answer this question.