如何根据列名称中包含的某些元素自动(或系统地)重新排列数据框的列。例如,
df <- data.frame(name_001_a=letters[1:4],
value_003_a=c(rep(TRUE, 2), rep(FALSE, 2)),
other_002_a=letters[5:8])
我想根据列名(001,002,003)中的数字重新排列列,因此我的数据框是:
> df <- df[c(1,3,2)]
name_001_a other_002_a value_003_a
1 a e TRUE
2 b f TRUE
3 c g FALSE
4 d h FALSE
如何使用大量变量有效地做到这一点? Thxs
答案 0 :(得分:1)
使用str_extract
个套件的stringr
library(stringr)
df[,order(str_extract(colnames(df),"[0-9]+"))]
# name_001_a other_002_a value_003_a
#1 a e TRUE
#2 b f TRUE
#3 c g FALSE
#4 d h FALSE
答案 1 :(得分:1)
以下是mixedsort
library(gtools)
df[mixedsort(names(df))]
# name_001_a other_002_a value_003_a
#1 a e TRUE
#2 b f TRUE
#3 c g FALSE
#4 d h FALSE
或gsub
df[order(as.integer(gsub("^[^0-9]+|[^0-9]+$", "", names(df))))]