使用dplyr contains()根据多个字符串选择列 [英] select columns based on multiple strings with dplyr contains()

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

问题描述

我想基于一个带有 regex 表达式的名称来选择多个列.我正在尝试使用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

但是它不适用于选择/包含方式:

However it doesn't work with the select/contains way:

mtcars %>% select(contains('m|ar'))
### data frame with 0 columns and 32 rows

怎么了?

推荐答案

您可以使用matches

 mtcars %>%
        select(matches('m|ar')) %>%
        head(2)
 #              mpg am gear carb
 #Mazda RX4      21  1    4    4
 #Mazda RX4 Wag  21  1    4    4

根据?select文档

‘matches(x,ignore.case = TRUE)’:选择所有变量 名称与正则表达式"x"匹配

‘matches(x, ignore.case = TRUE)’: selects all variables whose name matches the regular expression ‘x’

尽管contains使用单个字符串

mtcars %>% 
       select(contains('m'))

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

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