What about using ifelse()
to create a new factor?
x = factor(c("A","B","A","C","D","E","A","E","C"))
# chained comparisons, a single '|' works on the whole vector
y = as.factor(
ifelse(x=='A'|x=='B',
'A+B',
ifelse(x=='D'|x=='E','D+E','C')
)
)
> y
[1] A+B A+B A+B C D+E D+E A+B D+E C
Levels: A+B C D+E
# using %in% to search
z = as.factor(
ifelse(x %in% c('A','B'),
'A+B',
ifelse(x %in% c('D','E'),'D+E','C'))
)
> z
[1] A+B A+B A+B C D+E D+E A+B D+E C
Levels: A+B C D+E
If you don't want to hard-code in the factor level C
above, or if you have more than one factor level that does not need to be combined, you can use the following.
# Added new factor levels
x = factor(c("A","B","A","C","D","E","A","E","C","New","Stuff","Here"))
w = as.factor(
ifelse(x %in% c('A','B'),
'A+B',
ifelse(x %in% c('D','E'),
'D+E',
as.character(x) # without the cast it's numeric
)
)
)
> w
[1] A+B A+B A+B C D+E D+E A+B D+E C New Stuff Here
Levels: A+B C D+E Here New Stuff