I'm wondering if there is a way to use dplyr to change the levels of a factor before piping the data frame to ggplot(), in order to create more human-reader-friendly levels in a ggplot. Here's a toy example:
toy.df <- data.frame(originalVar = c("A", "B", "C", "D", "E"))
I've tried the following three ideas, but to no avail:
toy.df %>%
do(
levels(.$originalVar) <- c("V", "W", "X", "Y", "Z")
)
toy.df %>%
mutate(newVar = factor(.$originalVar, levels = c("V", "W", "X", "Y", "Z")))
toy.df %>%
mutate(
newVar = do(
factor(.$originalVar, levels = c("V", "W", "X", "Y", "Z"))
)
)
You can simply change the levels of the factor with levels() before calling ggplot(), or use ggplot(transform(...)), as was offered on SO here:
But, it feels like this could be accomplished in the dplyr pipeline, but I can't figure it out.
Once again, the end goal is to change the level labels in a ggplot boxplot or a faceted scatterplot to something more human-friendly, like can be accomplished with base::boxplot(..., names = c("V", "W", "X", "Y", "Z")).
Thanks for any ideas. Earl