简体   繁体   中英

how to select several columns based on grep?

Given a data frame data

     data <- data.frame(col1 = 1:5,                      # 
      Create example data
               famg = letters[1:5],
               xxm = letters[5:1],
               x2 = 5:1)
              data

I want to keep the columns that containe

     tokeep=c("col","xm","fa") 

I used

   data[grep(tokeep, names(data))] 

please note that tokeep is long than this example so i do not want to just use "col"|"xm"|"fa" but rather tokeep

I guess you can try

data[grep(paste0(tokeep,collapse = "|"),names(data))]

Does this work:

data[grep(paste(tokeep, collapse = '|'), colnames(data))]
  col1 famg xxm
1    1    a   e
2    2    b   d
3    3    c   c
4    4    d   b
5    5    e   a

alternative way with dplyr package

data %>% select(contains(tokeep))
  col1 xxm famg
1    1   e    a
2    2   d    b
3    3   c    c
4    4   b    d
5    5   a    e

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM