1

我使用 dcast 将 data.table 转换为宽格式。由于我现在有很多列(因为我在 var.values 参数中指定了多个变量,所以我想对列重新排序。这是我输入的数据的示例:

dt<-data.table(a_1=c(1,2,3), a_2=c(1,2,3), a_3=c(1,2,3), freq_1=c(1,2,3),freq_2=c(1,2,3), freq_3=c(1,2,3))

    a_1 a_2 a_3 freq_1 freq_2 freq_3
1:   1   1   1      1      1      1
2:   2   2   2      2      2      2
3:   3   3   3      3      3      3

它应该是这样的:

dt1<-data.table(a_1=c(1,2,3), freq_1=c(1,2,3), a_2=c(1,2,3), freq_2=c(1,2,3), a_3=c(1,2,3), freq_3=c(1,2,3))

   a_1 freq_1 a_2 freq_2 a_3 freq_3
1:   1      1   1      1   1      1
2:   2      2   2      2   2      2
3:   3      3   3      3   3      3

第一个提示是这样的:

library("gtools")
cdat <- colsplit(names(dt),"\\_",c("name","num"))
dt<-dt[,order(mixedorder(cdat$name),cdat$num)]

但这没有用,不幸的是

非常感谢您的帮助!

4

1 回答 1

2

你可以使用setcolorder

library(data.table)
setcolorder(dt, order(sub('.*_', '', names(dt))))

这使,

   a_1 freq_1 a_2 freq_2 a_3 freq_3
1:   1      1   1      1   1      1
2:   2      2   2      2   2      2
3:   3      3   3      3   3      3
于 2018-02-22T15:30:37.383 回答