# [R] Is R the right choice for simulating first passage times of random walks?

Paul Menzel paulepanter at users.sourceforge.net
Thu Jul 28 01:36:11 CEST 2011

```Dear R folks,

I need to simulate first passage times for iterated partial sums. The
related papers are for example .

As a start I want to simulate how long a simple random walk stays
negative, which should result that it behaves like n^(-½). My code looks
like this.

-------- 8< -------- code -------- >8 --------
n = 100000 # number of simulations

length = 100000 # length of iterated sum
z = rep(0, times=length + 1)

for (i in 1:n) {
x = c(0, sign(rnorm(length)))
s = cumsum(x)
for (i in 1:length) {
if (s[i] < 0 && s[i + 1] >= 0) {
z[i] = z[i] + 1
}
}
}
plot(1:length(z), z/n)
-------- 8< -------- code -------- >8 --------

This code already runs for over half an hour on my system¹.

Reading about the for loop  it says to try to avoid loops and I
probably should use a matrix where every row is a sample.

Now my first problem is that there is no matrix equivalent for
`cumsum()`. Can I use matrices to avoid the for loop?

My second question is, is R the right choice for such simulations? It
would be great when R can also give me a confidence interval(?) and also
try to fit a curve through the result and give me the rule of
correspondence(?) . Do you have pointers for those?

I glanced at simFrame  and read `?simulate` but could not understand
it right away and think that this might be overkill.

Do you have any suggestions?

Thanks,

Paul

¹ AMD Athlon(tm) X2 Dual Core Processor BE-2350, 2,1 GHz

 http://www-stat.stanford.edu/~amir/preprints/irw.ps
 http://arxiv.org/abs/0911.5456
 http://cran.r-project.org/doc/manuals/R-intro.html#Repetitive-execution
 https://secure.wikimedia.org/wikipedia/en/wiki/Function_(mathematics)
 http://finzi.psych.upenn.edu/R/library/simFrame/html/runSimulation.html
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part