Jeni
Jeni

Reputation: 958

How to sort a dataframe columns by the median of all its columns

How can I sort this datfarame by the median of its columns?

A    B    C

1    2    3
4    5    6
7    8    9
10   11   12

So, the output would be

C    B    A
3    2    1
6    5    4
9    8    7
12   11   10

I know, with this example, is easy to sort the dataframe by reverting the order of the columns, but, I would like to know how to sort the columns of this dataframe by the median of all of them.

Thanks!

Upvotes: 1

Views: 932

Answers (3)

akrun
akrun

Reputation: 887148

An option with tidyverse

library(dplyr)
library(tidyr)
df %>%
    summarise(across(everything(), median)) %>% 
    pivot_longer(everything()) %>%
    arrange(desc(value)) %>%
    pull(name) %>% 
    select(df, .)

Or using base R with apply

df[order(-apply(df, 2, median))]
#   C  B  A
#1  3  2  1
#2  6  5  4
#3  9  8  7
#4 12 11 10

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101403

Here is another base R solution

> df[names(sort(-sapply(df,median)))]
   C  B  A
1  3  2  1
2  6  5  4
3  9  8  7
4 12 11 10

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

Calculate median column-wise and order :

df[order(-sapply(df, median))]

#   C  B  A
#1  3  2  1
#2  6  5  4
#3  9  8  7
#4 12 11 10

You can also use colMedians from matrixStats to get column-wise median.

df[order(-matrixStats::colMedians(as.matrix(df)))]

data

df <- structure(list(A = c(1L, 4L, 7L, 10L), B = c(2L, 5L, 8L, 11L), 
C = c(3L, 6L, 9L, 12L)), class = "data.frame", row.names = c(NA, -4L))

Upvotes: 2

Related Questions