View Full Version : SPlus help


Che
04-14-2008, 01:30 PM
I'm fairly new to Splus.
I have a probabilty distribution:
P(Xj=-1) = 0.35
P(Xj=0)= 0.4
and P(Xj=1) = 0.25

and am looking at finding a function that simulates the summing of Xj variables. S(n)

e.g S(2) has
P(S(2)=0) = 0.335
P(S(2)=-1)= 0.280
P(S(2)=1) = 0.200
P(S(2)=-2) = 0.1225
and P(S(2)=2) = 0.0625

But I was to simulate this random walk for higher n in s-plus.
I've been hinted at the commands "sample", "cusum" and "tsplot" being helpful.
But I'm completely stuck!

BioStatMatt
04-14-2008, 07:33 PM
If you just want to simulate the sum of n random variates drawn from

P(Xj=-1) = 0.35
P(Xj=0)= 0.4
P(Xj=1) = 0.25

use the following function

rwalk <- function(n, steps, probs) {
u <- matrix(runif(n*steps), nrow = n, ncol = steps)
s <- rowSums(u > (1 - probs[3]) ) - rowSums(u < probs[1])
return(s)
}

if you want to simulate the sum N times taking M steps from 0 each time, use

S <- rwalk(N, M, c(0.35,0.4,0.25))

notice that you may also change the probabilities.

Just for fun, try this

hist(rwalk(1000, 10, c(0.35,0.4,0.25)))

You can see that the histogram is shifted negatively, as expected since 0.35 < 0.25.

-Matt