[R] How can I make this nested loop faster?

Suzen, Mehmet msuzen at gmail.com
Fri May 9 13:02:17 CEST 2014


Your code is not re-producable. Can you provide a working example
using a standard dataset from R?
But, you could first try to use compiler package, see ?enableJIT.
Another option would be to use  doMC/foreach packages if you can run
your assignment in the nested loop in parallel, see %dopar%.

On 8 May 2014 21:59, Ludwig Hilger <l.hilger at ku.de> wrote:
> Hello everybody,
> I have written a nested for-loop, but as length(uc) > 170,000, this would
> take VERY long. I have tried to use sapply or something but I cannot get it
> to work, I would be happy if someone could point out to write this more
> efficiently. Thank you all,
>
> Ludwig
>
> ergsens <- data.frame(budget = numeric(500))
> uc <- unique(rftab$startCell)
>
> for(i in 1:500){
> uniquerates <- rlnorm(n = length(uc), mean = -1.6, sd = 1.7)
>     for(j in 1:length(uc)){
>         rftab$masskg[rftab$startCell == uc[j]] <- uniquerates[j]
>     }
> ergsens$budget[i] <- sum(rftab$masskg, na.rm = TRUE)/1000
> }
>
>
>
>
>
> -----
> Dipl. Geogr. Ludwig Hilger
> Wiss. MA
> Lehrstuhl für Physische Geographie
> Katholische Universität Eichstätt-Ingolstadt
> Ostenstraße 18
> 85072 Eichstätt
> --
> View this message in context: http://r.789695.n4.nabble.com/How-can-I-make-this-nested-loop-faster-tp4690209.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