Skip to content

Instantly share code, notes, and snippets.

@mattmalin
Created June 29, 2012 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmalin/3017339 to your computer and use it in GitHub Desktop.
Save mattmalin/3017339 to your computer and use it in GitHub Desktop.
reordering factors
# example ordering of elements in a factor for use in a graph:
mock <- data.frame(
element = as.factor(c(rep("foo", 10), rep("bar", 10), rep("hello", 10))),
value = rnorm(30))
levels(mock$element)
# [1] "bar" "foo" "hello"
# defining custom order for the elements:
my_order <- as.character(c("hello", "foo", "bar"))
# example plot with elements in order 3,2,1:
ggplot(mock, aes(x = factor(element, levels = my_order), y = value)) + geom_point()
# if wanting to rearrange the order within the factor itself, can use levels
levels(mock$element) <- my_order
levels(mock$element)
# [1] "hello" "foo" "bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment