[R] Simulation

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Thu May 14 09:01:06 CEST 2009


Dimitris Rizopoulos wrote:
> Wacek Kusnierczyk wrote:
>> Barry Rowlingson wrote:
>>> 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
>>
>> indeed, for some, but only for some, values of m and n, it can actually
>> be half a hair faster than the matrix and the replicate approaches,
>> proposed earlier by others:
>
> another approach to create a matrix, a bit more efficient than using
> matrix() but also clean for beginners IMO, is to directly assign
> dimensions to a vector, e.g.,
>
> library(rbenchmark)
>
> n=100; m=100
> benchmark(replications=100, columns=c('test', 'elapsed'), order=NULL,
>     list={ l=list(); for (i in 1:n) l[[i]] = rnorm(m) },
>     liist={ l=vector('list', n); for (i in 1:n) l[[i]] = rnorm(m) },
>     matrix=matrix(rnorm(n*m), n, m),
>     matrix2 = {mat <- rnorm(n*m); dim(mat) <- c(n, m); mat},
>     replicate=replicate(m, rnorm(n))
> )

sure;  you could also replace 'matrix' with 'as.matrix' in the original
solution, which also gives some speedup:

n=100; m=100
benchmark(replications=1000, columns=c('test', 'elapsed'), order=NULL,
    list={ l=list(); for (i in 1:n) l[[i]] = rnorm(m) },
    liist={ l=vector('list', n); for (i in 1:n) l[[i]] = rnorm(m) },
    matrix=matrix(rnorm(n*m), n, m),
    matrix2 = {mat <- rnorm(n*m); dim(mat) <- c(n, m); mat},
    as.matrix=as.matrix(rnorm(n*m), n, m),
    replicate=replicate(m, rnorm(n))
)

# 3    matrix   0.173
# 4   matrix2   0.162
# 5 as.matrix   0.169

vQ




More information about the R-help mailing list