简体   繁体   中英

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. 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:

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.

>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.

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

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

data

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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