lunedì 4 giugno 2007

How do you get the most common row from a matrix?

If I have a matrix like this:

array(1:3,dim=c(4,5))

[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 1 2
[2,] 2 3 1 2 3
[3,] 3 1 2 3 1
[4,] 1 2 3 1 2


in which rows 1 and 4 are similar, I want to find that vector c(1,2,3,1,2).

library(cluster)
x <- array(1:3,dim=c(4,5))
dissim <- as.matrix(daisy(as.data.frame(x)))
dissim[!upper.tri(dissim)] <- NA
unique(x[which(dissim == 0, arr.ind=TRUE), ])


or

count <- table(apply(x, 1, paste, collapse=" "))
count[which.max(count)]

2 commenti:

  1. Hi, nice blog :)

    ## another way
    x <- array(1:3, dim = c(4,5))
    x[duplicated(x), ]
    [1] 1 2 3 1 2

    RispondiElimina
  2. Thank you!
    And thanks for the snippet too!

    RispondiElimina