Re: [R] Building a random walk vector

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
Date: Fri 04 Aug 2006 - 11:50:10 EST

On 8/3/2006 9:17 PM, Matthew Wilson wrote:
> I'm studying R in my free time. I want to build a vector where each
> element is equal to the element before it in the sequence plus some
> random tweak.
>
> In python, I would write:
>
> vec = [100] * 50 # make a 50-element list with each element set to 100
> from random import randint
> for i, v in enumerate(vec):
> if i is not 0: # if we're not on the first element
> vec[i] = vec[i-1] + randint(-2, 2)
>
> I suspect R has some fancier way of doing this. How to?

Assuming randint(-2, 2) gives a value uniform on (-2, 2) a quick way to do what you want is

vec <- 100 + c(0, cumsum(runif(49, -2, 2)))

Duncan Murdoch



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Fri Aug 04 11:54:15 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 04 Aug 2006 - 14:17:41 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.