Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a string from a list to select a column in R [duplicate]

Tags:

dataframe

r

I have a list of variable names and I want to use the strings from the list to access columns in data frames

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)

I have 2 uneven data frames and I want to create a new column by doing some basic maths

df1$Var4<-df1$Var1 + df2$Var1

Var4
2
3

But i want to be able to call the column names i'm adding together by refering to the list of variables names I have, I have tried the two following pieces of code by neither worked

df1$Var4<- df1$List[1]+df1$list[1]

and 

Z<-list[1]
df1$Var4 <- df1$Z + df2$Z

I don't want to hard code the column names because this will be creating a function to be used across data frames where the variable names will change

Any help would be much appreciated

like image 405
Dave Matteo Avatar asked Jul 22 '20 13:07

Dave Matteo


Video Answer


3 Answers

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
like image 189
Duck Avatar answered Oct 21 '22 13:10

Duck


To follow up with the reasoning to Duck's obviously correct answer, your approach isn't working for two reasons:

  1. The $ operator does "not allow computed indices", so you can't pass a character vector to it. See help(`$`).
`$`(df1,"Var1")
#[1] 1 2

`$`(df1,list[[1]])
#Error in df1$list[[1]] : invalid subscript type 'language'
  1. 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"
like image 3
Ian Campbell Avatar answered Oct 21 '22 15:10

Ian Campbell


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
like image 2
ThomasIsCoding Avatar answered Oct 21 '22 14:10

ThomasIsCoding