Johnny Johansson Johnny Johansson - 18 days ago 6
R Question

Picking the most common element from a number of factors

Lets say I have 3 factors, each has 2 levels: 'a' and 'b':

> b <- factor(c('b', 'b', 'a'))
> a <- factor(c('a', 'b', 'a'))
> c <- factor(c('a', 'a', 'a'))


I want to create fourth factor that on every position contains the most common element from this 3 factors, so, in this example, it would look like this:

> d
[1] a b a
Levels: a b


Is there a way of performing this kind of operation with some "smooth" function, or do I have to use "if" conditions?

Answer

We can try

factor(apply(data.frame(b, a, c), 1, Mode), levels = levels(a))
#[1] a b a
#Levels: a b

where Mode is

Mode <- function(x) {
 ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}
Comments