[R] matrix indexing and update

murali.menon at fortisinvestments.com murali.menon at fortisinvestments.com
Wed Nov 5 17:30:04 CET 2008


I have a matrix:

a <- matrix(rnorm(100), 10)

And a vector:

b <- rnorm(10)

Now, I want to switch the signs of those rows of a corresponding to 
indices in b whose values exceed the 75 %-ile of b

which(b > quantile(b)[4])
[1] 2 6 10

so I want, in effect:

a[2, ] <-  -a[2, ]
a[6, ] <- -a[6, ]
a[10, ] <- -a[10, ]

I thought I could do

a[which(b > quantile(b)[4]), ] <- -a

but that's clearly wrong. 

I came up with an sapply():

t(sapply(1 : NROW(a), function(n) ifelse(b > quantile(b)[4], -a[n, ], a[n, 


What's a good way to achieve this? 



This e-mail is confidential and may be privileged. If you have received it by mistake, please notify the sender by return e-mail and delete it from your system. You should not disclose, copy or use it for any purpose. The information in this e-mail is not contractual. Fortis Investments provides no guarantee as to the correctness of this information and accepts no responsibility for any action taken on the basis of it. Fortis Investments is the trade name for all entities within the Fortis Investment Management group.

More information about the R-help mailing list