如何根据列组的平均值对数据框进行重新排序 [英] How to reorder a data frame based on mean of column groups

查看:49
本文介绍了如何根据列组的平均值对数据框进行重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据与列ID关联的中位数对数据帧进行重新排序.

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

我有一个带有一列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

我想对该数据帧重新排序,以使列ID的顺序基于alpha列中相关值的递减方式:

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

这不成功:

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

推荐答案

尝试

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

这篇关于如何根据列组的平均值对数据框进行重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆