Changing factor levels with dplyr mutate
This is probably simple and I feel stupid for asking. I want to change the levels of a factor in a data frame, using mutate. Simple example:
library("dplyr")
dat <- data.frame(x = factor("A"), y = 1)
mutate(dat,levels(x) = "B")
I get:
Error: Unexpected '=' in "mutate(dat,levels(x) ="
Why is this not working? How can I change factor levels with mutate?
Solution 1:
With the forcats package from the tidyverse this is easy, too.
mutate(dat, x = fct_recode(x, "B" = "A"))
Solution 2:
I'm not quite sure I understand your question properly, but if you want to change the factor levels of cyl
with mutate()
you could do:
df <- mtcars %>% mutate(cyl = factor(cyl, levels = c(4, 6, 8)))
You would get:
#> str(df$cyl)
# Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...