简体   繁体   English

根据每一列中的特定值对数据框列进行排序

[英]sorting data frame columns based on specific value in each column

I am using the Tidyverse package in R. I have a data frame with 20 rows and 500 columns. 我在R中使用Tidyverse包。我有一个包含20行500列的数据框。 I want to sort all the columns based on the size of the value in the last row of each column. 我想根据每列最后一行中值的大小对所有列进行排序。

Here is an example with just 3 rows and 4 columns: 这是一个只有3行4列的示例:

1 2 3 4,
5 6 7 8,
8 7 9 1

The desired result is: 理想的结果是:

3 1 2 4,
7 5 6 8,
9 8 7 1

I searched stack overflow but could not find an answer to this type of question. 我搜索了堆栈溢出,但找不到此类问题的答案。

The following reorders the data frame columns by the order of the last-rows values: 以下内容按最后一行值的顺序对数据框列进行重新排序:

df <- data.frame(col1=c(1,5,8),col2=c(2,6,7),col3=c(3,7,9),col4=c(4,8,1))
last_row <- df[nrow(df),]
df <- df[,order(last_row,decreasing = T)]

First, to get the last rows. 首先,获取最后一行。 Then to sort them with the order() function and to return the reordered columns. 然后使用order()函数对它们进行排序,并返回重新排序的列。

>df
  col3 col1 col2 col4
1    3    1    2    4
2    7    5    6    8
3    9    8    7    1

If we want to use dplyr from tidyverse , we can use slice to get the last row and then use order in decreasing order to subset columns. 如果要使用dplyrtidyverse ,可以使用slice来获取最后一行,然后order decreasing使用order来对列进行子集化。

library(dplyr)

df[df %>% slice(n()) %>% order(decreasing = TRUE)]

#  V3 V1 V2 V4
#1  3  1  2  4
#2  7  5  6  8
#3  9  8  7  1

Whose translation in base R would be R基为谁的翻译是

df[order(df[nrow(df), ], decreasing = TRUE)]

data 数据

df <- read.table(text = "1 2 3 4
                         5 6 7 8
                         8 7 9 1")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM