[R] min and max operations on matrix

2010-01-20 Thread Murali.MENON
Folks, I've got a matrix x as follows: x - matrix(c(1,2,3,5,3,4,3,2,1), ncol = 3, byrow = TRUE) x [,1] [,2] [,3] [1,]123 [2,]534 [3,]321 In each row of x, I want to replace the minimum value by -1, the maximum value by +1 and all other values by 0.

Re: [R] min and max operations on matrix

2010-01-20 Thread Gabor Grothendieck
Try this: t(apply(x, 1, function(x) (x == max(x)) - (x == min(x [,1] [,2] [,3] [1,] -101 [2,]1 -10 [3,]10 -1 You can avoid the transpose using plyr: library(plyr) aaply(x, 1, function(x) (x == max(x)) - (x == min(x))) Var1 1 2 3 1 -1 0 1 2