Skip to content
Back to formatted view

Raw Message

Message-ID: <971536df1001201205g78427840s954f25621dd813f2@mail.gmail.com>
Date: 2010-01-20T20:05:36Z
From: Gabor Grothendieck
Subject: min and max operations on matrix
In-Reply-To: <5A3D018CBDC36B4F8FF6DB52DDF3B82D01C11F19@BE-S0500-V22.adroot.local>

Try this:

> t(apply(x, 1, function(x) (x == max(x)) - (x == min(x))))
     [,1] [,2] [,3]
[1,]   -1    0    1
[2,]    1   -1    0
[3,]    1    0   -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  1 -1  0
   3  1  0 -1

On Wed, Jan 20, 2010 at 11:57 AM,  <Murali.MENON at fortisinvestments.com> wrote:
> 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,] ? ?1 ? ?2 ? ?3
> [2,] ? ?5 ? ?3 ? ?4
> [3,] ? ?3 ? ?2 ? ?1
>
>
> 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.
>
> So in the above case I want to end up as follows:
>
> ? ? [,1] [,2] [,3]
> [1,] ? -1 ? ?0 ? ?1
> [2,] ? ?1 ? -1 ? ?0
> [3,] ? ?1 ? ?0 ? -1
>
> I tried the following, which seems to work:
>
>> t(apply(x, 1, function(y) {z <- numeric(NROW(y)); z[which.min(y)] <-
> -1; z[which.max(y)]<- 1; z}))
>
> Is there a neater way to do this?
>
> Thanks,
>
> Murali
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>