[R] Is there a faster way to do this?

Peter Alspach Peter.Alspach at plantandfood.co.nz
Fri Mar 26 02:38:13 CET 2010


Tena koe Marcio

Seems like you are simply multiplying transpose b by b and replacing the diagonal with 0.  If this is correct, then use

a <- t(b) %*% b
diag(a) <- 0

If this is not a correct interpretation of what you are trying to do, could you show us with a small reproducible example.

HTH .....

Peter Alspach

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Márcio Resende
> Sent: Friday, 26 March 2010 2:15 p.m.
> To: r-help at r-project.org
> Subject: [R] Is there a faster way to do this?
> 
> 
> Hi guys, I am still learning R, and not well familiar with all the
> apply
> functions.
> I am trying to find faster alternatives to replace the for cycle.
> Is there a faster way to do the example below?
> 
> nm <- 1000
> b <- matrix (rnorm (5000, 0, 1), nrow = 500, ncol = nm)
> a <- matrix (0, nm, nm)
> for (i in 1 : nm) {
> for (j in 1 : nm) {
> if ( j == i) {
> next }
> a[i, j] <- t (b [, i]) %*% b[, j]
> }
> }
> 
> thanks
> 
> --
> View this message in context: http://n4.nabble.com/Is-there-a-faster-
> way-to-do-this-tp1691601p1691601.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> 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.


More information about the R-help mailing list