Lennie
Lennie

Reputation: 363

Combine factors via majority vote into one in R

I have three factor vectors with the same number of levels like this:

eins <- c("no", "yes", "no")
zwei <- c("no", "no", "no")
drei <- c("yes", "yes", "no")

Now I would need to combine them based on the majority factor level. So in this example:

combined
[1] "no" "yes"   "no"

I know how to build a foor loop and then use if statements to create a new vector, but I wanted to know if there is a faster/better way in R.

Thanks for the help!

Upvotes: 2

Views: 270

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

Something like the following:

a <- apply(cbind(eins, zwei, drei), 1, table)
sapply(a, function(x) names(x)[which.max(x)])
#[1] "no"  "yes" "no"

Upvotes: 4

Related Questions