How to set levels in specific order?
The desired order of levels are - "CA", "IN", "FL" "NY"
library(dplyr)
tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
mutate(states_fct = factor(states))
Use the levels =
argument.
tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
mutate(states_fct = factor(states, levels = c("CA", "IN", "FL", "NY"))
You can use ordered
to express that you want an ordered factor:
states = ordered(c("FL", "NY", "CA", "IN"), levels = c("CA", "IN", "FL", "NY"))
str(states)
We could use fct_relevel
from forcats
package:
library(dplyr)
library(forcats)
tbl <- tibble(states = c("FL", "NY", "CA", "IN")) %>%
mutate(states_fct = factor(states)) %>%
mutate(states_fct = fct_relevel(states_fct, c("CA", "IN", "FL", "NY")))
levels(tbl$states_fct)
Output:
states states_fct
<chr> <fct>
1 FL FL
2 NY NY
3 CA CA
4 IN IN
> levels(tbl$states_fct)
[1] "CA" "IN" "FL" "NY"