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

时间:2016-06-30 15:25:44

标签: r sorting dataframe ggplot2 rank

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

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)
})

这就是我的图表的样子:

enter image description here

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

任何建议表示赞赏。谢谢你的时间!

2 个答案:

答案 0 :(得分:2)

使用@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")

enter image description here

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

答案 1 :(得分:0)

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