如何在 data.frame 中对 R 中每个因素的值进行排名

How to rank values in a data.frame for each factor in R

我有一个看起来像这样的数据集:

Subject <- rep(1:5, each = 3)
Condition <- rep(-1:1,5)
DV <- rnorm(15)
foo <- cbind(Subject,Condition,DV)
foo <- data.frame(foo)
foo <- within(foo, {
  Subject <- factor(Subject) #I'm converting subject to factor because that's how it is in my actual dataset
  Condition <- factor(Condition)
})

我的图表是这样的:

我想做的是重新组织数据,以便首先绘制条件 -1 的最大值的主题,然后绘制第二大值,依此类推。我希望我的图表看起来像这样:

如有任何建议,我们将不胜感激。感谢您的宝贵时间!

使用 @Procrastinatus's answer 中的 reorder 函数,你可以这样做:

ggplot(foo, aes(x = reorder(Subject, -rep(DV[Condition == -1], each = 3)), 
                y = DV, fill = Condition)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  xlab("subject")

注意:无法重现您的图表,因为您没有为随机抽样设置种子。

要以自定义方式重新排列条形图,使用 ggplot 的 scale_x_discrete 参数非常简单。

我首先使用 dplyr 计算出正确的顺序,但任何其他方法都可以。

library(dplyr)
myorder <- foo %>% filter(Condition==-1) %>% arrange(desc(DV)) %>% .$Subject

ggplot(data=foo) + 
  aes(x=Subject, y=DV, fill=Condition) + 
  geom_bar(stat="identity", position="dodge") + 
  scale_x_discrete(limits=myorder)