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?
How do I Rename Factor Levels in R? The simplest way to rename multiple factor levels is to use the levels() function. For example, to recode the factor levels “A”, “B”, and “C” you can use the following code: levels(your_df$Category1) <- c("Factor 1", "Factor 2", "Factor 3") .
One way to change the level order is to use factor() on the factor and specify the order directly. In this example, the function ordered() could be used instead of factor() . Another way to change the order is to use relevel() to make a particular level first in the list. (This will not work for ordered factors.)
mutate() is a dplyr function that adds new variables and preserves existing ones. That's what the documentation says. So when you want to add new variables or change one already in the dataset, that's your good ally. Given our dataset df , we can easily add columns with calculations.
The droplevels() function in R can be used to drop unused factor levels. This function is particularly useful if we want to drop factor levels that are no longer used due to subsetting a vector or a data frame. where x is an object from which to drop unused factor levels.
With the forcats package from the tidyverse this is easy, too.
mutate(dat, x = fct_recode(x, "B" = "A"))
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With