在 dplyr 中使用带有部分列名向量的 starts_with

mat*_*sho 4 r dplyr

我想使用 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')
Run Code Online (Sandbox Code Playgroud)

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

dplyr::select_(df, starts_with(vars))
Run Code Online (Sandbox Code Playgroud)

但是,上述方法不起作用。

Hon*_*Ooi 6

dplyr 中的各种选择辅助函数旨在仅采用单个字符串进行匹配。您可以通过将字符串组合成一个正则表达式并使用matches

vars <- paste0("^(", paste(vars, collapse="|"), ")")
select(df, matches(vars))
Run Code Online (Sandbox Code Playgroud)