[R] For Loop

MacQueen, Don m@cqueen1 @end|ng |rom ||n|@gov
Mon Sep 24 18:13:43 CEST 2018

In my opinion this is a pretty reasonable question for someone new to R.

Yes, it can be written without a for loop, and it would be better. Rich Heiberger gave a good solution early on, but I'd like to add an outline of the reasoning that leads to the solution.

You are taking the log of a ratio, and in the ratio, the numerator uses elements 2 through len, and the denominator uses elements 1 through (len-1). So, just write it that way:


or, taking advantage of using negative numbers when indexing vectors,


then take the log

   s <- log( c1[-1]/c1[-len] )

Comparing this with the loop version makes an example of why people say the R language is vectorized.

Do good R programmers make very little use of the for statement? Since R is vectorized, the for statement is necessary less often than in  non-vectorized languages. But "very little use" would be too broad a generalization. It will depend on what problems are being solved.

Finally, if using the loop in this case, it's true that s must exist before the statement is run. But that's not much of a problem. Just put
  s <- numeric( len-1)
before the loop.

Don MacQueen
Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
Lab cell 925-724-7509

On 9/22/18, 2:16 PM, "R-help on behalf of rsherry8" <r-help-bounces using r-project.org on behalf of 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?
    R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
    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