Wednesday, April 6, 2011

Changing the order of Factors (in plots)

use reorder

-> Here is the example from the internal help:

bymedian <- with(InsectSprays, reorder(spray, count, median))

boxplot(count ~ bymedian, data = InsectSprays,
xlab = "Type of spray", ylab = "Insect count",
main = "InsectSprays data", varwidth = TRUE,
col = "lightgray")


reorder(spray,count,median) reorders the factor levels of InsectSprays$spray (the first argument of reorder), not the factor itself;


the third argument of reorder - some aggregate function - operates on the column InsectSprays$count (the second argument of reorder) and defines therefore the new order.


In the example above the median of InsectSprays$count for each group of InsectSprays$spray is calculated, and the levels are reordered ascending according to the medians of each group.


look at the differences:

> InsectSprays$spray
[1] A A A A A A A A A A A A B B B B B B B B B B B B C C C C C C C C C C C C D D
[39] D D D D D D D D D D E E E E E E E E E E E E F F F F F F F F F F F F
Levels: A B C D E F
> with(InsectSprays, reorder(spray,count,median))
[1] A A A A A A A A A A A A B B B B B B B B B B B B C C C C C C C C C C C C D D
[39] D D D D D D D D D D E E E E E E E E E E E E F F F F F F F F F F F F
attr(,"scores")
A B C D E F
14.0 16.5 1.5 5.0 3.0 15.0
Levels: C E D A F B
> with(InsectSprays, reorder(spray,count,min))
[1] A A A A A A A A A A A A B B B B B B B B B B B B C C C C C C C C C C C C D D
[39] D D D D D D D D D D E E E E E E E E E E E E F F F F F F F F F F F F
attr(,"scores")
A B C D E F
7 7 0 2 1 9
Levels: C E D A B F

you can also use it in the definition of graphics:
library(lattice)
picture<-barchart(reorder(name, Freq) ~ Freq | iv, groups=dropout, data=zahlen, xlab='', stack=T, auto.key=list(text=c('Aktiv','dropout'), columns=2))

If you want to change the order of a factor without an aggregating function (e.g. if the levels have a natural order like "tiny, normal, big") read the post
Creating Factors

No comments :

Post a Comment