R: Sort columns from dcast output numerically, not lexicographically

This is an ordering of column names containing both numbers and text. I have a dataframe that sprang from dcastand has 200 rows. I have a problem with the order.

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 ordered columns:

names(DF) <- c('Testname1.1, Testname1.2,Testname1.3,...Testname1.100,Testname2.1,...Testname 2.100)

There is a column in the original input that indicates the day, but is not used when I "drop" the data. Is there a way to specify the "dcast" function to numerically arrange column names?

What would be the easiest way to get columns ordered as needed in R?

Thank you so much!

+4
source share
3

, , , :

library("reshape2")  ## for colsplit()
library("gtools")

:

dat <- data.frame(matrix(1:25,5))
names(dat) <- c('Testname1.1', 'Testname1.100',
     'Testname1.11','Testname1.2','Testname2.99')

:

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

mixedorder() ( @BondedDust) , , (Testnamexx) 9 , Testname1, Testname2, Testname10 .

+3

pkg: gtools , , , , . , , .

    nvec <- c('Testname1.1', 'Testname1.100', 'Testname1.11', 'Testname1.2', 'Testname2.99')
#------------
> require(gtools)
Loading required package: gtools

Attaching package: ‘gtools’

The following objects are masked from ‘package:boot’:

    inv.logit, logit
#------------
myvec <- nvec[order( mixedorder( sapply(strsplit(nvec, "\\."), "[[", 1)),
                  as.numeric(sapply(strsplit(nvec, "\\."), "[[", 2))  )
              ]
+3

:

library(gtools) #use gtools library
library(NCmisc) #use NCmisc library for pad.left()

myvec <- c('Testname1.1', 'Testname1.100','Testname1.11','Testname1.2','Testname2.99') #construct your vector

myvec[mixedorder(  paste(substring(myvec,1,9), pad.left(substring(myvec,11,100),'0') , sep='')  ) ] 

[1] "Testname1.1"   "Testname1.2"   "Testname1.11"  "Testname1.100" "Testname2.99"
+1

All Articles