我有一个包含数百列的数据框,这是一个简化的示例:
I need to arrange the order of specific columns so they are "kept together" based on the prefix in their column names, i.e. v_1, v_2, v_3 and spr_1, spr_2, spr_3 in the sample given. So the desired arrangement should look like this:
由于原始数据框中的列数量巨大,因此需要通过指定前缀(例如“spr_”)来选择列,而不是显式选择每一列(例如 c(spr_1, spr_2, spr_3))。
如果有必要,使用 tidyverse 的方法很棒,因为我已经使用了该库。
样本数据:
library(tidyverse)
df <- data.frame(
v_1 = c('A', 'B', 'C'),
xyz = c(1,2,3),
spr_1 = c('AA', 'BB', 'CC'),
spr_2 = c('DD', 'EE', 'FF'),
v_2 = c('D', 'E', 'F'),
quert = c('X', 'G', 'T'),
spr_3 = c('GG', 'HH', 'II'),
v_3 = c('G', 'H', 'I')
)