关于正则表达式:根据字符串匹配选择列-dplyr :: select

Select columns based on string match - dplyr::select

我有一个包含很多列的数据框("数据")。 一些列包含某个字符串(" search_string")。

如何使用dplyr::select()给我一个子集,只包括包含字符串的列?

我试过了:

1
2
3
4
5
# 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()接受数值向量来替代列,例如:

1
select(data,5,7,9:20)

但是我不知道如何从我的grepl()表达式中获取列ID的数字矢量。


在dplyr世界中,尝试:

1
select(iris,contains("Sepal"))

有关starts_withends_with等的许多其他帮助器,请参见?select中的"选择"部分。


你可以试试:

1
select(data, matches("search_string"))

它比contains更通用-您可以使用正则表达式(例如"one_string|or_the_other")。

有关更多示例,请参见:http://rpackages.ianhowson.com/cran/dplyr/man/select.html。


无需使用select,只需使用[

1
data[,grepl("search_string", colnames(data))]

让我们尝试使用iris数据集

1
2
3
4
5
6
7
8
>iris[,grepl("Sepal", colnames(iris))]
  Sepal.Length Sepal.Width
1          5.1         3.5
2          4.9         3.0
3          4.7         3.2
4          4.6         3.1
5          5.0         3.6
6          5.4         3.9


基于Piotr Migdals的响应,我想给出一个替代解决方案,以实现字符串向量的可能性:

1
2
3
4
myVectorOfStrings <- c("foo","bar")
matchExpression <- paste(myVectorOfStrings, collapse ="|")
# [1]"foo|bar"
df %>% select(matches(matchExpression))

使用正则表达式OR运算符(|)