Using a string from a list to select a column in R
Try this:
list<-list("Var1", "Var2", "Var3")
df1 <- data.frame("Var1" = 1:2, "Var2" = c(21,15), "Var3" = c(10,9))
df2<- data.frame("Var1" = 1, "Var2" = 16, "Var3" = 8)
#Sum
df1$Var4<- df1[,list[[1]]]+df2[,list[[1]]]
Var1 Var2 Var3 Var4
1 1 21 10 2
2 2 15 9 3
To follow up with the reasoning to Duck's obviously correct answer, your approach isn't working for two reasons:
- The
$
operator does "not allow computed indices", so you can't pass a character vector to it. Seehelp(`$`)
.
`$`(df1,"Var1")
#[1] 1 2
`$`(df1,list[[1]])
#Error in df1$list[[1]] : invalid subscript type 'language'
- You were trying to subset
df1
with a list. You need a character vector.
list[1]
#[[1]]
#[1] "Var1"
class(list[1])
#[1] "list"
The [[
operator selects an individual element from a list. In this case, the character vector you needed.
list[[1]]
#[1] "Var1"
class(list[[1]])
#[1] "character"
You can try the code below
df1$Var4 <- Map(`+`,df1,df2)[[lst[[1]]]]
such that
> df1
Var1 Var2 Var3 Var4
1 1 21 10 2
2 2 15 9 3