Home > Software design >  Filter a matrix by column name using column from another data set or list
Filter a matrix by column name using column from another data set or list

Time:10-26

I have a matrix like this:

df1

ABC    DEF      GHI      JKL
1       2        8        2
3       8        9        5
3       2        1        9

Then another df that has a column

df2

ID

ABC
DEF
GHI

Can I filter the matrix based on column name so only those that are in the ID column are kept? I tried:

list<-as_list(df2$ID)

df3<-df1[colnames(df1)%in% list,]

I want to get


ABC    DEF      GHI      
1       2        8        
3       8        9        
3       2        1        


CodePudding user response:

This should do your selection

df1[, intersect(colnames(df1), as.character(df2$ID)]

Or using your approach

df1[, colnames(df1) %in%  as.character(df2$ID)]

I used as.character(df2$ID) to coerce df2$ID (if they were factor) to be character for correct matching

CodePudding user response:

We may do

library(dplyr)
df1 %>%
    select(any_of(df2$ID))
  •  Tags:  
  • r
  • Related