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!