Adrian
Adrian

Reputation: 9793

Taking the majority vote across matrix columns in R

mymat <- structure(c(1, 1, 1, -1, -1, -1, -1, 1, -1, 1, 1, 1, 1, 1, -1
), .Dim = c(3L, 5L))

> mymat
     [,1] [,2] [,3] [,4] [,5]
[1,]    1   -1   -1    1    1
[2,]    1   -1    1    1    1
[3,]    1   -1   -1    1   -1

I want to take the majority vote across the columns of mymat. In this example, the majority vote results across the 5 columns are: 1 -1 -1 1 1.

I've tried looking at the solutions from a similar question here, but since the columns in mymat are unnamed, these solutions did not work for me.

Upvotes: 1

Views: 323

Answers (2)

lroha
lroha

Reputation: 34291

If you have binary voting of the type represented by your sample data you can use sign() and colSums():

sign(colSums(mymat))
[1]  1 -1 -1  1  1

Upvotes: 1

akrun
akrun

Reputation: 886928

We can use Mode function from here

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

and use apply with MARGIN as 2 for columnwise application of the function

apply(mymat, 2, Mode)
#[1]  1 -1 -1  1  1

Or using asplit/sapply

sapply(asplit(mymat, 2), Mode)

NOTE: Both the solutions work on a general dataset and not just based on the values showed by the OP

mymat2 <- cbind(c('A', 'B', 'A'), c('e', 'e', 'f'))
sapply(asplit(mymat2, 2), Mode)

Upvotes: 0

Related Questions