将dplyr中的starts_with与部分列名称的向量一起使用 [英] Using starts_with in dplyr with a vector of partial column names

查看:82
本文介绍了将dplyr中的starts_with与部分列名称的向量一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用dplyr选择与字符串向量匹配的某些列。

I would like to use dplyr to select certain columns that match to a string vector.

one <- seq(1:10)
two <- rnorm(10)
three <- runif(10, 1, 2)
four <- -10:-1

df <- data.frame(one, two, three, four)

vars <- c('on', 'thr')

我只想选择df中标题以 on或 thr开头的列:

I want to select only the columns in df whose titles start with'on' or 'thr':

dplyr::select_(df, starts_with(vars))

但是,上面的方法不起作用。

However, the above is not working.

推荐答案

dplyr中的各种选择帮助器函数均应采用只匹配一个字符串。通过将字符串组合成一个正则表达式并使用 matches

The various selection helper functions in dplyr are meant to take only a single character string for matching. You can get around this by combining your strings into one regular expression and using matches:

vars <- paste0("^(", paste(vars, collapse="|"), ")")
select(df, matches(vars))

这篇关于将dplyr中的starts_with与部分列名称的向量一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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