Combining factor level in R
This is now easy to do with fct_collapse()
from the forcats
package.
x <- factor(c("A","B","A","C","D","E","A","E","C"))
library(forcats)
fct_collapse(x, AB = c("A","B"), DE = c("D","E"))
#[1] AB AB AB C DE DE AB DE C
#Levels: AB C DE
One option is recode
from car
library(car)
recode(x, "c('A', 'B')='A+B';c('D', 'E') = 'D+E'")
#[1] A+B A+B A+B C D+E D+E A+B D+E C
#Levels: A+B C D+E
It should also work with dplyr
library(dplyr)
df %>%
mutate(x= recode(x, "c('A', 'B')='A+B';c('D', 'E') = 'D+E'"))
# x
#1 A+B
#2 A+B
#3 A+B
#4 C
#5 D+E
#6 D+E
#7 A+B
#8 D+E
#9 C
data
df <- data.frame(x)