I have data frame df. I want to select to the columns which names starts with q6, q7, q8, q9, q10 and q11.
If I write this expression it works :
sub_df = df %>%
select( matches("^q(6|7|8|9|10|11)")
How could I do using the : (seq) function ? Something likeselect( matches("^q(6:11)")
or 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
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
set.seed(24)
df <- as.data.frame(matrix(rnorm(12 *4), ncol = 12,
dimnames = list(NULL, paste0("q", 1:12))))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.