Shima Shima - 11 days ago 5
R Question

Select the variables in one dataframe from a list in another dataframe

I have a big data with large number of columns and rows. I want to subset few columns in df1 from a list of variables (the name of the columns in df1) in df2. Just for example, I have

df1 <- data.frame(A=sample(1:10, 10), B=sample(1:10, 10), C=sample(1:10,10), D=sample(1:10,10))
var <- c('A','C')
ratio <- c(0.5,0.6)
df2 <- data.frame(var,ratio)


New dataframe should look like this:

A C
1 9 2
2 1 3
3 4 5
4 2 8
5 10 7
6 5 1
7 7 9
8 3 4
9 8 10
10 6 6

Answer

We need to convert the factor variable 'var' to class for subsetting the first dataset

df1[as.character(df2$var)]
Comments