This is about ordering column names that contain both numbers and text. I have a dataframe which resulted from dcast
and has 200 rows. I have a problem with the ordering.
The column names are in the following format:
names(DF) <- c('Testname1.1', 'Testname1.100','Testname1.11','Testname1.2',...,Testname2.99)
Edit: I would like to have the columns ordered as:
names(DF) <- c('Testname1.1, Testname1.2,Testname1.3,...Testname1.100,Testname2.1,...Testname 2.100)
The original input has a column which specifies the day, but it is not being used when I 'cast' the data. Is there a way to specify the 'dcast' function to order combined column names numerically?
What would be the easiest way to get the columns ordered as I need to in R?
Thanks a lot!
I think you need to split the column before you can use it to order the data frame:
library("reshape2") ## for colsplit()
library("gtools")
Construct test data:
dat <- data.frame(matrix(1:25,5))
names(dat) <- c('Testname1.1', 'Testname1.100',
'Testname1.11','Testname1.2','Testname2.99')
Split and order:
cdat <- colsplit(names(dat),"\\.",c("name","num"))
dat[,order(mixedorder(cdat$name),cdat$num)]
## Testname1.1 Testname1.2 Testname1.11 Testname1.100 Testname2.99
## 1 1 16 11 6 21
## 2 2 17 12 7 22
## 3 3 18 13 8 23
## 4 4 19 14 9 24
## 5 5 20 15 10 25
The mixedorder()
above (borrowed from @BondedDust's answer) is not really necessary for this example, but would be needed if the first (Testnamexx
) component had more than 9 elements, so that Testname1
, Testname2
, and Testname10
would come in the proper order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With