根据字符串匹配选择列 - dplyr :: select [英] Select columns based on string match - dplyr::select

查看:164
本文介绍了根据字符串匹配选择列 - dplyr :: select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



我试过:

 #列为布尔向量
select(data,grepl(search_string,colnames(data)))

#列为列名称向量
select(data,colnames(data)[grepl(search_string,colnames(data))])

它们都不工作。



我知道 select()接受数字向量替代列例如:

  select(data,5,7,9:20)
/ pre>

但是我不知道如何从我的$ $中获取一列数列向量 ID c $ c> grepl()表达式。

解决方案

dplyr 世界,尝试:

  select(iris,contains(Sepal))

请参阅中的选择部分?为许多其他帮助者选择,如 starts_with ends_with 等。


I have a data frame ("data") with lots and lots of columns. Some of the columns contain a certain string ("search_string").

How can I use dplyr::select() to give me a subset including only the columns that contain the string?

I tried:

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

Neither of them work.

I know that select() accepts numeric vectors as substitute for columns e.g.:

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

But I don't know how to get a numeric vector of columns IDs from my grepl() expression.

解决方案

Within the dplyr world, try:

select(iris,contains("Sepal"))

See the Selection section in ?select for numerous other helpers like starts_with, ends_with, etc.

这篇关于根据字符串匹配选择列 - dplyr :: select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆