根据dplyr的多个字符串选择列 [英] select columns based on multiple strings with dplyr
本文介绍了根据dplyr的多个字符串选择列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据其名称使用正则表达式表达式选择多个列。我试图用 dplyr
包的管道语法来完成。我检查了其他主题,但只找到了一个单一的字符串的答案。
I want to select multiple columns based on their names with a regex expression. I am trying to do it with the piping syntax of the dplyr
package. I checked the other topics, but only found answers about a single string.
使用基本R:
library(dplyr)
mtcars[grepl('m|ar', names(mtcars))]
### mpg am gear carb
### Mazda RX4 21.0 1 4 4
### Mazda RX4 Wag 21.0 1 4 4
它不适用于select / contains方式:
However it doesn't work with the select/contains way:
mtcars %>% select(contains('m|ar'))
### data frame with 0 columns and 32 rows
有什么问题? / p>
What's wrong?
推荐答案
您可以使用匹配
mtcars %>%
select(matches('m|ar')) %>%
head(2)
# mpg am gear carb
#Mazda RX4 21 1 4 4
#Mazda RX4 Wag 21 1 4 4
根据?选择
文档
'matches(x,ignore.case = TRUE)':选择
名称匹配正则表达式x的所有变量
‘matches(x, ignore.case = TRUE)’: selects all variables whose name matches the regular expression ‘x’
虽然包含
使用单个字符串
mtcars %>%
select(contains('m'))
这篇关于根据dplyr的多个字符串选择列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文