r - find the max frequency per row in a matrix whith multiple max -
i have matrix this:
mat=matrix(c(1,1,1,2,2,2,3,4, 4,4,4,4,4,3,5,6, 3,3,5,5,6,8,0,9, 1,1,1,1,1,4,5,6),nrow=4,byrow=true) print(mat) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 1 1 1 2 2 2 3 4 [2,] 4 4 4 4 4 3 5 6 [3,] 3 3 5 5 6 8 0 9 [4,] 1 1 1 1 1 4 5 6
i find out number of row of matrix in can find objects max frequency, have more 1 max. in case, obtein new vector this:
[,1] [1,] "1" [2,] "3"
or similar. focus on index of row more 1 max.
we can use apply
margin=1
loop on rows. frequency of each unique element tabulate
, check whether equal max
value (==
) , use which
numeric index. return max
value if there ties.
lst <- apply(mat, 1, function(x) {x1 <- tabulate(x) which(x1 == max(x1)) })
if there single max
value per row, output vector
or else list
output.
if need extract elements have more 1 max
lst[lengths(lst)>1]
Comments
Post a Comment