On Jan 5, 2011, at 10:03 AM, Young Cho wrote:
Hi,
I am doing some simulations and found a bottle neck in my R script.
I made
an example:
a = matrix(rnorm(5000000),1000000,5)
tt = Sys.time(); sum(a[,1]*a[,2]*a[,3]*a[,4]*a[,5]); Sys.time() - tt
[1] -1291.026
Time difference of 0.2354031 secs
tt = Sys.time(); sum(apply(a,1,prod)); Sys.time() - tt
[1] -1291.026
Time difference of 20.23150 secs
Is there a faster way of calculating sum of products (of columns, or
of
rows)?
You should look at crossprod and tcrossprod.
And is this an expected behavior?
Yes. For loops and *apply strategies are slower than the proper use of
vectorized functions.
Thanks for your advice in advance,
--
David Winsemius, MD
West Hartford, CT
______________________________________________
R-help@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.