我想通过字符串匹配来排序数据帧的列。
library(dplyr)
data <- data.frame(start_a = 1,
start_f = 3,
end_a = 5,
end_f = 7,
middle_a= 9,
middle_f = 11)
- 例如,我想选择
start_f, start_a, middle_f, middle_a, end_f ,end_a
- 我正在尝试使用
data %>% select(matches("(start|middle|end)_(f|a)")))
这样做,以便我在匹配中键入的顺序是我希望选择的列的顺序。 - 期望输出为
data[c(2,1,6,5,4,3)]
您可以按照outer
所需的顺序构建列。
order1 <- c('start', 'middle', 'end')
order2 <- c('f', 'a')
cols <- c(t(outer(order1, order2, paste, sep = '_')))
cols
#[1] "start_f" "start_a" "middle_f" "middle_a" "end_f" "end_a"
data[cols]
# start_f start_a middle_f middle_a end_f end_a
#1 3 1 11 9 7 5
如果数据中没有order1
和order2
的所有组合,我们可以使用any_of
,它将只选择data
中存在的列而不会产生任何错误。
library(dplyr)
data %>% select(any_of(cols))
根据名称中的模式进行选择。
order1 <- c('start', 'middle', 'end')
order2 <- c('f', 'a')
pattern <- c(t(outer(order1, order2, function(x, y) sprintf('^%s_%s.*', x, y))))
pattern
#[1] "^start_f.*" "^start_a.*" "^middle_f.*" "^middle_a.*" "^end_f.*" "^end_a.*"
cols <- names(data)
data[sapply(pattern, function(x) grep(x, cols))]
# start_f start_a middle_f middle_a end_f end_a
#1 3 1 11 9 7 5