R syntax question

Joined
6/6/08
Messages
1,194
Points
58
Guys, quick question...

Say I have a matrix with ties for a certain value (max or min), but there's a tie. How do I get back the indices of those columns?

For instance, say our matrix is

434
122
331

I want my output to be:

1,3
2,3
1,2

Furthermore, if I have another matrix, I'd like to take those indices and add the corresponding column indices of those same rows.

So say our second matrix is:
235
159
672

I want my output to be:
7
14
13

What would be the syntax to do this?

Edit: for the record, the function apply(matrixName,1,which.max) does not work. It only returns one value at a time, and therefore, defeats the entire purpose.
 
a <- t(matrix(c(4,3,4,1,2,2,3,3,1), 3, 3))
a

b <- t(matrix(c(2,3,5,1,5,9,6,7,2), 3, 3))
b

idx <- do.call(rbind, lapply(1:nrow(a), function(n.row) {
return(which(a[n.row,]==max(a[n.row,])))
}))
idx

out <- do.call(rbind, lapply(1:nrow(idx), function(n.row) {
return(sum(b[n.row, idx[n.row,]]))
}))
out

If a was:
4 4 4
1 2 2
3 3 1

where the elements equal to the max are 3 elements wide whereas the other 2 are only 2 elements wide, I'd make placeholders as 0 in the creation of idx so the rbind has the same number of columns, since referencing to 0 won't affect the sum, e.g.:

idx
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 3 0
[3,] 1 2 0

b[1,0]
numeric(0)

sum(5+b[1,0]) = 5
 
Thanks a lot. I since solved the problem using customized apply functions, but it seems we have similar procedures.
 
Back
Top Bottom