根据字符串匹配选择列 - dplyr::select [英] Select columns based on string match - dplyr::select
问题描述
我有一个包含很多列的数据框(数据").某些列包含某个字符串(search_string").
I have a data frame ("data") with lots and lots of columns. Some of the columns contain a certain string ("search_string").
如何使用 dplyr::select()
给我一个子集,其中只包含包含字符串的列?
How can I use dplyr::select()
to give me a subset including only the columns that contain the string?
我试过了:
# columns as boolean vector
select(data, grepl("search_string",colnames(data)))
# columns as vector of column names names
select(data, colnames(data)[grepl("search_string",colnames(data))])
它们都不起作用.
我知道 select()
接受数字向量作为列的替代,例如:
I know that select()
accepts numeric vectors as substitute for columns e.g.:
select(data,5,7,9:20)
但我不知道如何从我的 grepl()
表达式中获取列 ID
的数字向量.
But I don't know how to get a numeric vector of columns ID
s from my grepl()
expression.
推荐答案
在 dplyr 世界中,尝试:
select(iris,contains("Sepal"))
请参阅 ?select
中的选择部分,了解许多其他帮助程序,例如 starts_with
、ends_with
等.
See the Selection section in ?select
for numerous other helpers like starts_with
, ends_with
, etc.
这篇关于根据字符串匹配选择列 - dplyr::select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!