Reputation: 958
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
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
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
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