[R] For Loop

Ista Zahn |@t@z@hn @end|ng |rom gm@||@com
Sun Sep 23 19:32:50 CEST 2018


On Sun, Sep 23, 2018 at 10:09 AM Wensui Liu <liuwensui using gmail.com> wrote:
>
> Why?

The operations required for this algorithm are vectorized, as are most
operations in R. There is no need to iterate through each element.
Using Vectorize to achieve the iteration is no better than using
*apply or a for-loop, and betrays the same basic lack of insight into
basic principles of programming in R.

And/or, if you want a more practical reason:

> c1 <- 1:1000000
> len <- 1000000
> system.time( s1 <- log(c1[-1]/c1[-len]))
   user  system elapsed
  0.031   0.004   0.035
> system.time(s2 <- Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))
   user  system elapsed
  1.258   0.022   1.282

Best,
Ista

>
> On Sun, Sep 23, 2018 at 7:54 AM Ista Zahn <istazahn using gmail.com> wrote:
>>
>> On Sat, Sep 22, 2018 at 9:06 PM Wensui Liu <liuwensui using gmail.com> wrote:
>> >
>> > or this one:
>> >
>> > (Vectorize(function(i) log(c1[i + 1] / c1[i])) (1:len))
>>
>> Oh dear god no.
>>
>> >
>> > On Sat, Sep 22, 2018 at 4:16 PM 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.
>> >
>> > ______________________________________________
>> > 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.




More information about the R-help mailing list