[R] How can I make this nested loop faster?
William Dunlap
wdunlap at tibco.com
Thu May 8 22:15:40 CEST 2014
I cannot run your code because not all the variables are defined, but
try not doing the nested replacements, rftab$masskg[...] <- newValue,
in the loop. Instead, pull out masskg as a new stand-along object
before the start of the loop and put it back into rftab at the end of
the loop. E.g., something like
masskg <- rftab$masskg
for(i in 1:500){
uniquerates <- rlnorm(n = length(uc), mean = -1.6, sd = 1.7)
for(j in 1:length(uc)){
masskg[rftab$startCell == uc[j]] <- uniquerates[j]
}
ergsens$budget[i] <- sum(masskg, na.rm = TRUE)/1000
}
rftab$masskg <- masskg
# and you may as well remove masskg now.
If that doesn't help enough, look into the ave() function or the
functions in plyr.
Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Thu, May 8, 2014 at 12:59 PM, 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