0

I have a data frame such as the following:

df <- data.frame(type=c("A", "A", "B"), var1 = c(2,4,3), var2 = c(6,1,2))
df
  type var1 var2
1    A    2    6
2    A    4    1
3    B    3    2

I want to iteratively perform calculations with these variables and for each iteration i, I need to assign the variables according to the variable names and the i-th row, e.g. in iteration 2, type should be "A", var1 should be 4 and var2 should be 1.

It can be easily done using the following code:

for(i in 1:nrow(df)){
type <- df[i,1]
var1 <- df[i,2]
var2 <- df[i,3]
}

However, I will not know the amount of variables and the variable names of df in advance.

Is there a simple and elegant solution? Thanks in advance!

elmo
  • 265
  • 1
  • 10
  • This sounds like a job for `?lapply`. You can use it to look through the columns of your data.frame and return a named list. – lmo Mar 24 '19 at 17:49
  • I was trying ```lapply``` together with ```assign```, but did not manage to get it working. Would you care to elaborate further and maybe post an answer? – elmo Mar 24 '19 at 17:56
  • It is typically recommended to work with named lists rather than to assign separate objects into your environment. See Gregor's post to [this question](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) for a good motivation as to why this is a good idea. If you *really* want to have separate objects, you can always use `list2env` after your `lapply`. – lmo Mar 24 '19 at 18:03

0 Answers0