I would like combine level "A","B" into "A+B". I successfully did this by the following:
x <- factor(c("A","B","A","C","D","E","A","E","C"))
x
#[1] A B A C D E A E C
#Levels: A B C D E
l <- c("A+B","A+B","C","D+E","D+E")
factor(l[as.numeric(x)])
#[1] A+B A+B A+B C D+E D+E A+B D+E C
#Levels: A+B C D+E
Is there any more trivial way to do this? (ie more explainable function name such as combine.factor(f, old.levels, new.levels) would help to understand the code easier.)
Also, I try to find a well named function which probably work with data frame in dplyr package but no luck. The closest implementation is
df %>% mutate(x = factor(l[as.numeric(x)]))
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
df <- data.frame(x)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.