简体   繁体   English

|R] 选择多个以相同模式开头的列

[英]|R] Select multiple columns starting with the same pattern

I have data frame df.我有数据框 df。 I want to select to the columns which names starts with q6, q7, q8, q9, q10 and q11.我想选择名称以 q6、q7、q8、q9、q10 和 q11 开头的列。

If I write this expression it works :如果我写这个表达式,它会起作用:

sub_df = df %>% select( matches("^q(6|7|8|9|10|11)") sub_df = df %>% select( matches("^q(6|7|8|9|10|11)")

How could I do using the : (seq) function ?我怎么能使用 : (seq) 函数? Something like就像是
select( matches("^q(6:11)")
or select( matches("^q(6-11)")select( matches("^q(6-11)")

But it does not work.但它不起作用。 I am quite new using this regular expression.我对这个正则表达式很陌生。

How could I do it ?我怎么办?

Thanks谢谢

df %>% select(starts_with(paste("q",6:11, sep = "")))

We could use regex to match the 'q' from the start ( ^ ) of the string followed by the range of values 6-9 within [] or ( | ) the 1 followed by range of [0-1] at the end ( $ ) of the string我们可以使用正则表达式从字符串的开头 ( ^ ) 匹配 'q',然后是[]内的值6-9范围或 ( | ) 1 后跟[0-1]的范围在末尾 ( $ ) 的字符串

library(dplyr)
df %>%
    select(matches('^q([6-9]|1[0-1])$'))

-output -输出

          q6          q7          q8         q9        q10         q11
1 -0.07430856 -0.64859151 -0.11629639  0.6128514 -4.4695644  0.06735770
2 -0.60515695 -0.09411013 -0.94382724  1.5171225  0.3690450  0.01710596
3 -1.70964518 -0.08554095 -0.03373792  0.6573804  0.1692267 -0.34365937
4 -0.26869311  0.11953107 -0.58542756 -1.0741813 -1.8221903 -0.66789220

data数据

set.seed(24)
df <- as.data.frame(matrix(rnorm(12 *4), ncol = 12, 
    dimnames = list(NULL, paste0("q", 1:12))))

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

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