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

时间:2022-04-10 00:07:05

How do I select multiple columns by name without having to type out each name.

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

For example I have the following code:

例如,我有以下代码:

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))

All the columns are in order but instead of selecting by number like below

所有列都按顺序排列,而不是像下面那样用数字选择

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

I would like to select by the name of the column.

我想通过列的名称进行选择。

Thank you!

2 个解决方案

#1


3  

You should use grep or grepl

你应该使用grep或grepl

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

or

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

#2


1  

If you need to do this as part of a pipe, you can also use dplyr::select and its helper functions in two equivalent ways, including one that can avoid regular expressions:

如果你需要在管道中做这个,你也可以用两种等价的方式使用dplyr :: select及其辅助函数,包括一个可以避免使用正则表达式的函数:

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

#1


3  

You should use grep or grepl

你应该使用grep或grepl

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

or

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

#2


1  

If you need to do this as part of a pipe, you can also use dplyr::select and its helper functions in two equivalent ways, including one that can avoid regular expressions:

如果你需要在管道中做这个,你也可以用两种等价的方式使用dplyr :: select及其辅助函数,包括一个可以避免使用正则表达式的函数:

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