[R] For Loop

Jeff Newmiller jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Sun Sep 23 03:45:52 CEST 2018


I do use for loops a few times per month, but only wrapped around large chunks of vectorized calculations, not for this kind of use case. In those cases I also pre-allocate output vectors/lists (e.g. vector( "list", len )) to avoid memory thrashing as you grow lists or other vectors one element at a time (v <- c( v, new value ) is an inefficient trick). I also create variables to hold intermediate results that would yield the same answer each time before going into the loop (e.g. exp(1)).

As regards your toy example, I would use a one-liner:

s <- diff( log( c1 ) )

which avoids executing exp(1) at all, much less every time through the loop, and it uses vectorized incremental subtraction rather than division (laws of logarithms from algebra). The default base for the log function is e, so it is unnecessary to specify it. Note that your loop calculates logs involving all but the first and last elements of c1 twice... once when indexing for i+1, and again in the next iteration of the loop it is accessed as index i.

You would be surprised how many iterative algorithms can be accomplished with cumsum and diff. Bill Dunlap has demonstrated examples quite a few times in the mailing list archives if you have time  to search.

On September 22, 2018 2:16:27 PM PDT, rsherry8 <rsherry8 using 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 using 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.

-- 
Sent from my phone. Please excuse my brevity.




More information about the R-help mailing list