简体   繁体   English

在dplyr中将starts_with与部分列名称的向量一起使用

[英]Using starts_with in dplyr with a vector of partial column names

I would like to use dplyr to select certain columns that match to a string vector. 我想使用dplyr选择与字符串向量匹配的某些列。

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')

I want to select only the columns in df whose titles start with'on' or 'thr': 我只想选择df中标题以“ on”或“ thr”开头的列:

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

However, the above is not working. 但是,上述方法不起作用。

The various selection helper functions in dplyr are meant to take only a single character string for matching. dplyr中的各种选择帮助器函数仅用于采用单个字符串进行匹配。 You can get around this by combining your strings into one regular expression and using matches : 您可以通过将字符串组合成一个正则表达式并使用matches来解决此问题:

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

Presumably you know in advance, because you're coding it in, what column name matches you want, so you could use 大概您已经预先知道了(因为您正在对其进行编码),因此所需的列名匹配,因此您可以使用

select(starts_with("on"), starts_with("thr"))

Ah, I see Tony Ladson essentiall suggested this already. 嗯,我已经看到Tony Ladson本质建议了。 Depending on your exact use case, though, I don't see a need to get them from a vector. 但是,根据您的确切用例,我认为不需要从向量中获取它们。

Here is a solution using starts_with : 这是使用starts_with的解决方案:

df %>% 
  select(map(c('on', 'thr'), 
             starts_with, 
             vars = colnames(.)) %>% 
         unlist())

Basically, the idea is to apply the starts_with function to the vector of names by using map . 基本上,这个想法是通过使用mapstarts_with函数应用于名称向量。 But to get it to work, one must add the argument vars (the list of colnames), and then unlist the result of map to get the vector of positions. 但要得到它的工作,必须添加参数vars (colnames的列表),然后选择不公开的结果map获得位置的向量。

This solution expands the one of Chrisss to the case where there are several matches for at least one entry. 此解决方案将Chrisss中的一个扩展为至少有一个条目有多个匹配项的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM