Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining factor level in R [duplicate]

Tags:

r

dplyr

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)]))
like image 339
alberthkcheng Avatar asked Apr 12 '16 09:04

alberthkcheng


People also ask

How do I combine two factors in R?

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.

How do you combine factors?

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.

How do I extract a level from a factor in R?

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).

Can you add factors in R?

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()


1 Answers

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
like image 182
Joe Avatar answered Oct 08 '22 17:10

Joe