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
CodePudding user response:
I guess you can try
data[grep(paste0(tokeep,collapse = "|"),names(data))]
CodePudding user response:
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
CodePudding user response:
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