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? (i.e. 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)]))
To combine two factor vectors, we can extract the unique levels of both the vectors then combine those levels. This can be done by using unique function. Also, we can set the levels of the original vectors to the combination of the levels, in this way, we can complete both the vectors with missing levels.
There are different ways of combining factors. A simple approach is to average stock weights across a number of single factor indexes – a composite index approach. A variant of this approach is to use a composite of the target factors to create a factor index – a composite factor approach.
To extract the factor levels from factor column, we can simply use levels function. For example, if we have a data frame called df that contains a factor column defined with x then the levels of factor levels in x can be extracted by using the command levels(df$x).
The command used to create or modify a factor in R language is – factor() with a vector as input. The two steps to creating a factor are: Creating a vector. Converting the vector created into a factor using function factor()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With