Visualizzazione post con etichetta comparing. Mostra tutti i post
Visualizzazione post con etichetta comparing. Mostra tutti i post

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

lunedì 14 maggio 2007

Comparing two matrices, row by row

ar1 <- array(data=c(1:16),dim=c(4,4))
ar2 <- array(data=c(1,2,3,3,5:16),dim=c(4,4))
z<-ar1==ar2
ar1
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
ar2
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 3 8 12 16
z
[,1] [,2] [,3] [,4]
[1,] TRUE TRUE TRUE TRUE
[2,] TRUE TRUE TRUE TRUE
[3,] TRUE TRUE TRUE TRUE
[4,] FALSE TRUE TRUE TRUE
which(z==FALSE)
[1] 4


Or

apply(ar1==ar2,1,all)