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

如何为R中的每个因子对data.frame中的值进行排序,r,sorting,dataframe,ggplot2,rank,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

我有一个类似以下内容的数据集:

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

Subject使用中的
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(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\u x\u 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)
库(dplyr)
myorder%筛选器(条件==-1)%%>%arrange(描述(DV))%%>%。$Subject
ggplot(数据=foo)+
aes(x=受试者,y=DV,填充=条件)+
几何图形栏(stat=“identity”,position=“dodge”)+
比例x离散(限值=myorder)

要以自定义方式重新排列条形图,使用ggplot的
scale\u x\u 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)
库(dplyr)
myorder%筛选器(条件==-1)%%>%arrange(描述(DV))%%>%。$Subject
ggplot(数据=foo)+
aes(x=受试者,y=DV,填充=条件)+
几何图形栏(stat=“identity”,position=“dodge”)+
比例x离散(限值=myorder)

可能有用:我认为代码不起作用,因为我有3个条件,不是1也请看这个问题和答案:可能有用:我认为代码不起作用,因为我有3个条件,不是1也请看这个问题和答案: