Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping 2 levels of a factor in R [duplicate]

Tags:

r

I have a column of data that is a factor with levels A, B and C, I am interested in combining two of these levels into one factor, so it would become A and B, with B = B and C, or maybe a new variable A and D, with D = B and C. I can come up with plenty of ways to do this by looping through the column with if statements, but I feel like there should be a more elegant approach and I was wondering if someone could point me in the right direction.

like image 959
asjohnson Avatar asked Mar 07 '12 15:03

asjohnson


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.

Can you group by a factor in R?

In this approach to group factor levels, the user has to simply call the levels() functions with the required parameters as required by the user, and then it will be leading to the new factor level as specified by the user in other words we will be merging two-factor levels into one category in the R programming ...

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


1 Answers

Use levels(x) <- ... to specify new levels, and to combine some previous levels. For example:

f <- factor(LETTERS[c(1:3, 3:1)]) f [1] A B C C B A Levels: A B C 

Now combine "A" and "B" into a single level:

levels(f) <- c("A", "A", "C") f [1] A A C C A A Levels: A C 
like image 152
Andrie Avatar answered Oct 11 '22 15:10

Andrie