Reputation: 3502
I have this data.frame
df <- data.frame(x = c("gravel", "sandstone", "siltstone"))
I want to rename the levels of the variable x by adding "R1_
" before the name of the levels. I can do it following this answer.
df %>% dplyr::mutate(x = fct_recode(x,
"R1_gravel" = "gravel",
"R1_sandstone" = "sandstone",
"R1_siltstone" = "siltstone"
))
x
1 R1_gravel
2 R1_sandstone
3 R1_siltstone
However, in my actual data.frame, variable x has many levels. So, it is time taking to rename all the levels as above. I wonder if there is a faster way to rename all the levels through adding R1_ at the start.
Upvotes: 4
Views: 4522
Reputation: 3597
Do this
levels(df$x) <- paste0("R1_",levels(df$x))
# df
# x
# 1 R1_gravel
# 2 R1_sandstone
# 3 R1_siltstone
Upvotes: 3