How to reorder a data frame based on mean of column groups

末鹿安然 提交于 2021-02-16 15:08:42

问题


I am trying to reorder a data frame based on the median value associated with a column ID.

I have a dataframe with a column of IDs and 2 columns of values.

ID <- c("a","a","a","b","b","b","c","c","c","c")
alpha <- c(3,4,5,9,11,13,1,1,1,0)
beta <- c(2,3,4,3,4,5,4,5,6,7)
df <- data.frame(ID,alpha,beta)

   ID alpha beta
1   a     3    2
2   a     4    3
3   a     5    4
4   b     9    3
5   b    11    4
6   b    13    5
7   c     1    4
8   c     1    5
9   c     1    6
10  c     0    7

I want to reorder this dataframe so that the column ID is in an order based on the decending means of the associated values in the alpha column:

   ID alpha beta
1   b     9    3
2   b    11    4
3   b    13    5
4   a     3    2
5   a     4    3
6   a     5    4
7   c     1    4
8   c     1    5
9   c     1    6
10  c     0    7

This was unsuccessful:

df[reorder(df$ID, df$alpha, FUN = mean),]

回答1:


Try

library(dplyr)
df %>% group_by(ID) %>% mutate(m = mean(alpha)) %>% arrange(desc(m)) %>% select(-m)
# A tibble: 10 x 3
# Groups:   ID [3]
       ID alpha  beta
   <fctr> <dbl> <dbl>
 1      b     9     3
 2      b    11     4
 3      b    13     5
 4      a     3     2
 5      a     4     3
 6      a     5     4
 7      c     1     4
 8      c     1     5
 9      c     1     6
10      c     0     7



回答2:


Here is an option using data.table

library(data.table)
setDT(df)[df[, mean(alpha), ID][order(-V1), .(ID)], on = .(ID)]
#    ID alpha beta
#1:  b     9    3
#2:  b    11    4
#3:  b    13    5
#4:  a     3    2
#5:  a     4    3
#6:  a     5    4
#7:  c     1    4
#8:  c     1    5
#9:  c     1    6
#10: c     0    7

Or we can use ave from base R to get the mean and then order

df[with(df, order(-ave(alpha, ID))),]


来源:https://stackoverflow.com/questions/46008444/how-to-reorder-a-data-frame-based-on-mean-of-column-groups

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!