[R] matrix indexing and update

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Wed Nov 5 17:42:52 CET 2008


you almost have it, e.g., check the following:

set.seed(123)
a <- matrix(rnorm(100), 10)
b <- rnorm(10)

ind <- b > quantile(b, 0.75)
a[ind, ] <- -a[ind, ]
a


I hope it helps.

Best,
Dimitris


murali.menon at fortisinvestments.com wrote:
> Folks,
> 
> I have a matrix:
> 
> set.seed(123)
> 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, 
> ])))
> 
> Ugh.
> 
> What's a good way to achieve this? 
> 
> Thanks,
> 
> Murali
> 
> 
> ---------------------------------------------------------------------------
> 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.
> 
> ______________________________________________
> 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.
> 

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014



More information about the R-help mailing list