c1 <- 1:1000000 len <- 1000000 system.time( s1 <- log(c1[-1]/c1[-len]) ) s <- c1[-len] system.time( for (i in 1:(len-1)) s[i] <- log(c1[i+1]/c1[i]) ) all.equal(s,s1)
> > c1 <- 1:1000000 > len <- 1000000 > system.time( + s1 <- log(c1[-1]/c1[-len]) + ) user system elapsed 0.032 0.005 0.037 > s <- c1[-len] > system.time( + for (i in 1:(len-1)) s[i] <- log(c1[i+1]/c1[i]) + ) user system elapsed 0.226 0.002 0.232 > all.equal(s,s1) [1] TRUE > much faster, and much easier to understand when vectorized On Sat, Sep 22, 2018 at 5:16 PM, rsherry8 <rsher...@comcast.net> wrote: > > It is my impression that good R programmers make very little use of the for > statement. Please consider the following > R statement: > for( i in 1:(len-1) ) s[i] = log(c1[i+1]/c1[i], base = exp(1) ) > One problem I have found with this statement is that s must exist before the > statement is run. Can it be written without using a for > loop? Would that be better? > > Thanks, > Bob > > ______________________________________________ > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > 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@r-project.org mailing list -- To UNSUBSCRIBE and more, see 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.