[R] “For” calculation is so slow

Petr PIKAL petr.pikal at precheza.cz
Wed May 23 09:30:19 CEST 2012


> 
> I'm not sure what you are trying to prove with that example - the 
loopless
> versions are massively faster, no?

In some languages loops are integral part of programming habits. In R you 
can many things do with whole objects without looping - vectorisation 
approach. See R-Inferno from Patrick Burns - circle 3.

> 
> I don't disagree that loops are sometimes unavoidable, and I suppose
> sometimes loops can be faster when the non-loop version e.g. breaks your

Hm. I am not sure what it has to do with memory budget.

> memory budget, or performs tons of needless computations. But I think
> avoiding for loops whenever you can is a good rule of thumb in R coding.

I constantly use loops when I create pictures of dataframe values. 

This

library(ggplot2)
pdf("konc.pdf", 8,8, useDingbats=F)
for (i in columns) {
p<-ggplot(df.name, aes(x=x.value, y=df.name[,i], colour=other.column))
print(p+geom_smooth(method="lm")+geom_point(aes(shape=some.factor, 
size=5))+scale_y_continuous(names(df.name)[i]))
}
dev.off()

can easily create pdf file with many plots of selected columns against one 
column. I know that I could use lapply, but the loop seems to me clean and 
efficient even when I plot several hundreds graphs.

Regards
Petr

> 
> --
> View this message in context: http://r.789695.n4.nabble.com/For-
> calculation-is-so-slow-tp4630830p4630897.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