Home > front end >  Select columns based on another column in a different data frame in R
Select columns based on another column in a different data frame in R

Time:10-23

I have a df:

AA <- c("GA","GA", "GA","GA","GA")
A <- c(1,2,3,4,5)
B <- c(5,4,3,2,1)
C <- c(2,3,4,5,1)
D <- c(4,3,2,1,5)
df <- data.frame(AA, A, B, C, D)

The other df is:

E <- c("B", "D")
F <- c("GA","GA")
df2 <- data.frame(E, F)

I would like to only select the columns from df based on the values from df2$E. And that data frame would look like this:

AA <- c("GA","GA", "GA","GA","GA")
B <- c(5,4,3,2,1)
D <- c(4,3,2,1,5)
df3 <- data.frame(AA, B, D)

My current code below gives me a empty data frame with 0 obs and 5 variables

df3 <- df %>% filter(df %in% df2$E)

Any assistance in generating a code that works would be greatly appreciated. Thank you!

CodePudding user response:

Here we can index via column names.

df[,c("AA",df2$E)]
  •  Tags:  
  • r
  • Related