【问题标题】:How to rank values in a data.frame for each factor in R如何为 R 中的每个因素对 data.frame 中的值进行排名
【发布时间】:2016-11-02 19:20:23
【问题描述】:

我有一个如下所示的数据集:

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 的最大值的主题,然后绘制第二个最大值,依此类推。我希望我的图表看起来像这样:

感谢任何建议。感谢您的宝贵时间!

【问题讨论】:

标签: r sorting dataframe ggplot2 rank


【解决方案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")

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

【讨论】:

    【解决方案2】:

    要以自定义方式重新排序条形图,使用 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)
    

    【讨论】:

      猜你喜欢
      • 2011-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      相关资源
      最近更新 更多