# NOT RUN {
## EXAMPLE 1 - no aggregation ##
## Make a fake data set
dat <- aggregate(cbind(mpg, hp, disp)~carb, mtcars, mean)
dat$carb <- factor(dat$carb)
## compare levels (data set looks the same though)
dat$carb
reorder_by(carb, ~-hp + -mpg, data = dat)$carb
library(ggplot2)
## Unordered bars
ggplot(dat, aes(x=carb, y=mpg)) +
geom_bar(stat="identity") +
coord_flip()
## Ordered bars
ggplot(reorder_by(carb, ~mpg, dat), aes(x=carb, y=mpg)) +
geom_bar(stat="identity") +
coord_flip()
## Return just the vector with new levels
reorder_by(carb, ~-hp + -mpg, dat, df=FALSE)
## EXAMPLE 2 - with aggregation ##
mtcars2 <- reorder_by(gear, ~hp + -carb, mtcars, mean)
## Without re-leveling gear
ggplot(mtcars, aes(mpg, hp)) +
geom_point(aes(color=factor(cyl))) +
facet_grid(gear~.)
## After re-leveling gear
ggplot(mtcars2, aes(mpg, hp)) +
geom_point(aes(color=factor(cyl))) +
facet_grid(gear~.)
# }
Run the code above in your browser using DataLab