按名称选择多个列,而无需键入每个名称

时间:2018-02-09 18:47:32

标签: r select multiple-columns names

如何按名称选择多个列,而无需键入每个名称。

例如,我有以下代码:

CTDB[, c(
"ENJOY_TV_RADIO_CHILD", 
"ENJOY_FMLY_CLOSE_FRND_CHILD", 
"ENJOY_HOBBIES_CHILD", 
"ENJOY_FAV_MEAL_CHILD",
"ENJOY_SHOWER_CHILD", 
"ENJOY_SCENT_CHILD", 
"ENJOY_PPL_SMILE_CHILD", 
"ENJOY_LOOK_SMART_CHILD", 
"ENJOY_READ_CHILD", 
"ENJOY_FAV_DRINK_CHILD", 
"ENJOY_SMALL_THINGS_CHILD", 
"ENJOY_LANDSCAPE_CHILD", 
"ENJOY_HELP_OTHR_CHILD", 
"ENJOY_PRAISE_CHILD")] <-revalue(as.matrix(CTDB[, c(
"ENJOY_TV_RADIO_CHILD", 
"ENJOY_FMLY_CLOSE_FRND_CHILD",
"ENJOY_HOBBIES_CHILD", 
"ENJOY_FAV_MEAL_CHILD", 
"ENJOY_SHOWER_CHILD", 
"ENJOY_SCENT_CHILD", 
"ENJOY_PPL_SMILE_CHILD", 
"ENJOY_LOOK_SMART_CHILD", 
"ENJOY_READ_CHILD", '
"ENJOY_FAV_DRINK_CHILD", 
"ENJOY_SMALL_THINGS_CHILD", 
"ENJOY_LANDSCAPE_CHILD", 
"ENJOY_HELP_OTHR_CHILD", 
"ENJOY_PRAISE_CHILD")]), c("0"=3, "1"=2, "2"=1, "3"=0))

所有列都按顺序排列,而不是按照下面的数字选择

CTDB[,74:87] <-revalue(as.matrix(CTDB[,74:87]), c("0"=3, "1"=2, "2"=1, "3"=0))

我想通过列名来选择。

谢谢!

2 个答案:

答案 0 :(得分:3)

您应该使用grepgrepl

CTBD[,grep("^ENJOY.*CHILD$",colnames(CTBD)]

CTBD[,grepl("^ENJOY.*CHILD$",colnames(CTBD)]

答案 1 :(得分:1)

如果您需要将此作为管道的一部分,您还可以使用dplyr::select及其辅助函数以两种等效方式使用,包括可以避免使用正则表达式的方法:

CTBD %>% select(matches("^ENJOY.*CHILD$"))
CTBD %>% select(intersect(starts_with("ENJOY"), ends_with("CHILD")))