Description Usage Arguments Value Author(s) References Examples
Create a new dataframe with a factor reordered (re-leveled) by numeric variable(s).
1 |
fact |
The factor to be reordered (re-leveled). |
by |
A formula to order the factor by. |
data |
A |
FUN |
A function to compute the summary statistics which can be applied to all data subsets. |
df |
logical. If |
Returns a re-ordered (re-leveled) dataframe, factor vector, or levels.
Thomas Wutzler and Tyler Rinker <tyler.rinker@gmail.com>.
The majority of this code is taken directly from Thomas Wutzler's blog post that has since been removed/redirected.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | ## 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~.)
## End(Not run)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.