Antje Rosebrock
Antje Rosebrock

Reputation: 15

Reordering columns with multiple variables in var.values after dcast

I have used dcast to put a data.table into a wide format. Since I have many columns now (because I specified multiple variables in the var.values argument, I'd like to reorder the columns. This is an example for the data I have entered:

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

This is how it should look like:

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

First hint was something like:

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

But this did not work, unfortunately

Thank you very much for your help!

Upvotes: 1

Views: 137

Answers (1)

Sotos
Sotos

Reputation: 51592

You can use setcolorder,

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

which gives,

   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

Upvotes: 2

Related Questions