[R] Simulation

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Thu May 14 08:45:17 CEST 2009

Barry Rowlingson wrote:


>>> Yes, you can probably vectorize this with lapply or something, but I
>>> prefer clarity over concision when dealing with beginners...
>> but where's the preferred clarity in the for loop solution?
>  Seriously? You think:
>  lapply(1:n, rnorm, 0, 1)
> is 'clearer' than:
> x=list()
> for(i in 1:n){
>   x[[i]]=rnorm(i,0,1)
> }
> for beginners?
>  Firstly, using 'lapply' introduces a function (lapply) that doesn't
> have an intuitive name. Also, it takes a function as an argument. The
> concept of having a function as a parameter to another function is
> something that a lot of programming beginners have trouble with -
> unless they were brought up on LISP of course, and few of us are.
>  I propose that the for-loop example is clearer to a larger population
> than the lapply version. 

there's one more issue.  the lapply solution effectively hides the loop
variable from the user, keeping h{im,er} from doing things that should
not be done, e.g., assignment to the loop variable inside the loop with
the assumption that it has an impact on the looping condition.

for example, this simple c code

    int i;
    for (i = 0; i < 5; i++) {
       i = 5;
       printf("%d\n", i); }

will print *one* 5, while this simple r code (as well as analogous code
in many other scripting languages)

    for (i in 0:4) {
       i = 5
       print(i) }

will print *five* 5s.  it's not magic, but if the 'beginner' comes from
c, that's a possibly ugly surprise, which needs further ado.  we have
recently seen on this list an example of how a user was changing looping
variables within the loop body and was surprised it didn't work.  with
lapply, you simply can't get at that.  not so easily, at least.

that said, i don't think there is anything wrong with for looping vs.
lapply, but the r inferno i referred to originally *is* a source of
interesting comments explaining good and bad practices.


More information about the R-help mailing list