[R] Simulation

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Wed May 13 20:07:10 CEST 2009


On Wed, May 13, 2009 at 5:36 PM, Wacek Kusnierczyk
<Waclaw.Marcin.Kusnierczyk at idi.ntnu.no> wrote:
> Barry Rowlingson wrote:

>>  Soln - "for" loop:
>>
>>  > z=list()
>>  > for(i in 1:1000){z[[i]]=rnorm(100,0,1)}
>>
>> now inspect the individual bits:
>>
>>  > hist(z[[1]])
>>  > hist(z[[545]])
>>
>> If that's the problem, then I suggest she reads an introduction to R...
>
> i'd suggest reading the r inferno by pat burns [1], where he deals with
> this sort of for-looping lists the way it deserves ;)

 I don't think extending a list this way is too expensive. Not like
doing 1000 foo=rbind(foo,bar)s to a matrix. The overhead for extending
a list should really only be adding a single new pointer to the list
pointer structure. The existing list data isn't copied.

Plus lists are more flexible. You can do:

 z=list()
 for(i in 1:1000){
  z[[i]]=rnorm(i,0,1)  # generate 'i' samples
}

and then you can see how the properties of samples of rnorm differ
with increasing numbers of samples.

Yes, you can probably vectorize this with lapply or something, but I
prefer clarity over concision when dealing with beginners...

Barry




More information about the R-help mailing list