raju raju - 6 months ago 19
R Question

How to extract all the columns from a data frame based on a column in another data frame?

I have two data frames. I want to extract all the columns from a data frame based on another data frame column.

df1:

sample
GY
AP
A9
MB
AU

df2:

num start end length GY A9 MB AP JK GH AU
2 23 24 567 5 6 7 8 9 0 1
2 3 44 57 8 6 7 3 4 0 9
2 234 54 67 5 6 7 8 9 0 1

result:
num start end length GY A9 MB AP AU
2 23 24 567 5 6 7 8 1
2 3 44 57 8 6 7 3 9
2 234 54 67 5 6 7 8 1


I tried in this way but it didn't work out:

u <- df1[df1$sample %in% colnames(df2),]


Can anyone tell me how to do this?

Answer Source

With:

df2[, c(1:4, which(colnames(df2) %in% df1$sample))]

you get:

  num start end length GY A9 MB AP AU
1   2    23  24    567  5  6  7  8  1
2   2     3  44     57  8  6  7  3  9
3   2   234  54     67  5  6  7  8  1

And this also works:

df2[, c(rep(TRUE,4), tail(colnames(df2) %in% df1$sample, -4))]