简体   繁体   English

数据集中的列从指定行中的最大值到最小值

[英]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.

相关问题 将R中的每一行从最大值重新排列为最小值 - Rearranging each row from largest value to smallest value in R 一列中从小到大的顺序号 (R) - Order numbers from smallest to largest in a column (R) 如何从两列中找到最大值和最小值 - How can I find largest value and smallest value from two Columns 如果指定值与使用 R 的行相对应,如何将宽数据集中的列名作为长数据集中的行 - How to bring column name from wide dataset as row in long dataset if specified value corresponded with row using R 在 R 中查找我的数据集中的最小和最大日期 - Finding the smallest and largest date in my dataset in R 将R中的数据框从一列中的值最大到最小排序 - Sort a data frame in R largest to smallest from value in a column 累积频率从最大到最小 - Cumulative frequency from largest to smallest 如何在 R 的数据帧列表中按第二行从大到小对列进行水平排序? - How to sort the columns horizontally largest-to-smallest by second row in list of data frames in R? 使用dplyr :: order造成麻烦,将值从最小到最大(包括小于1的正整数)进行排序 - Trouble using dplyr::order to rank values from smallest to largest including positive integers smaller than 1 如何按组从最小到最大对 R 数据帧中的多列进行排序? - How to sort multiple columns in R data frame from smallest to largest by group?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM