简体   繁体   中英

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

I have a dataset that looks something like this:

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

And this is how my graph looks like:

在此处输入图片说明

What I would like to do is reorganize the data so that the subject with the largest value for condition -1 is plotted first, then second largest value plotted second and so on. I would like my graph to look like this: 在此处输入图片说明

Any suggestion is appreciated. Thank you for your time!

Use the reorder function from @Procrastinatus's answer , you can do something like:

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

在此处输入图片说明

Note: Can't reproduce your graph because you didn't set a seed for the random sampling.

To reorder your bars in a customized way, the use of the scale_x_discrete argument of ggplot is quite straightforward.

I first calculated the right order with dplyr but any other way is fine.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM