[英]Order Columns in Dataset from Largest to Smallest Value in A Specified Row
Suppose I have a dataset: 假设我有一个数据集:
library(data.table)
dat1<-data.table(id=c(111,111,111,222,222,222), year=c(1995,1996,1997,1995,1996,1997), value=c(4,5,1,2,6,7))
How do I order the columns of the dataset based on the size of the values in row 1 (or an arbitrary row). 如何根据第1行(或任意行)中值的大小对数据集的列进行排序。
I want my output to be: 我希望我的输出是:
dat2<-data.table(value=c(4,5,1,2,6,7),id=c(111,111,111,222,222,222), year=c(1995,1996,1997,1995,1996,1997)
Because in dat1 row 1, value 4 is the smallest value making "dat1$value" column 1, id 111 is second smallest value making "dat1$id" column 2 and year 1995 is biggest value making "dat1$year" column 3. 因为在dat1行1中,值4是“ dat1 $ value”列1的最小值,id 111是在“ dat1 $ id”列2的第二个最小值,而1995年是“ dat1 $ year”列的第二个最大值。
You can do setcolorder
你可以做
setcolorder
setcolorder(dat1, names(dat1)[order(dat1[1])])
dat1
value id year
1: 4 111 1995
2: 5 111 1996
3: 1 111 1997
4: 2 222 1995
5: 6 222 1996
6: 7 222 1997
Method 2 方法二
dat1 = dat1[,names(dat1)[order(dat1[1,])],with=F]
value id year
1: 4 111 1995
2: 5 111 1996
3: 1 111 1997
4: 2 222 1995
5: 6 222 1996
6: 7 222 1997
Recommend by RonakShah 由RonakShah推荐
dat1[, order(dat1[1, ]), with = FALSE]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.