问题描述
这是关于对同时包含数字和文本的列名称进行排序.我有一个来自dcast
的数据框,并且有200行.我的订购有问题.
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.
列名采用以下格式:
names(DF) <- c('Testname1.1', 'Testname1.100','Testname1.11','Testname1.2',...,Testname2.99)
我想按以下顺序排列各列:
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)
原始输入具有指定日期的列,但是当我投射"数据时未使用该列.有没有一种方法可以指定'dcast'函数来对组合的列名称进行数字排序?
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?
按照我在R中需要进行排序的最简单方法是什么?
What would be the easiest way to get the columns ordered as I need to in R?
非常感谢!
推荐答案
我认为您需要先拆分列,然后才能使用它对数据框进行排序:
I think you need to split the column before you can use it to order the data frame:
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
,,并且Testname10
将按照正确的顺序排列.
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.
这篇关于R:按数字顺序而不是按字典顺序对dcast输出中的列进行重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!