[R] Odp: how to speed up this for loop?

From: Petr PIKAL <petr.pikal_at_precheza.cz>
Date: Tue, 22 Jul 2008 14:40:26 +0200

Hi

r-help-bounces_at_r-project.org napsal dne 22.07.2008 01:24:05:

>
> Could anyone tell me a better way to achieve the output of this for
loop? It
> seems to run quite slow. I'm sure there must be a more consise way to
sum
> from FN to LN, excluding positive values, for each row.

It is difficult to understand what you really want as we do not have R, FN, LN and Temp.

> vec<-rnorm(100)
> sum(vec[vec<0])

[1] -45.72518

Gives you sum of vec values which are lower than zero. It shall be easy to extend it to set of vectors or matrix.

> mat<-rnorm(120)
> dim(mat)<-c(10,12)
> apply(mat, 2, function(x) sum(x[x<0]))
 [1] -0.9543727 -3.9965437 -6.7924017 -1.4949170 -3.8042263 -6.5552674 -2.6386912 -3.3587444 -6.3740483 -3.1178593 -7.2580333 -3.2709297

There are other options but you shall follow posting guide to obtain better answers.

Regards
Petr

>
> #sum between FN and LN, excluding positive values
> for(i in 1:R){
> for(j in FN[i]:LN[i]){
> if(Temp[i,j]<0)
> sum[i] <- sum[i] + sum(Temp[i,j])}}
>
> Cheers,
> R
> --
> View this message in context:
http://www.nabble.com/how-to-speed-up-this-for-
> loop--tp18579577p18579577.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.



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. Received on Tue 22 Jul 2008 - 12:45:53 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 22 Jul 2008 - 13:32:06 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive