-2

I have a random walk function

random.walk = function(n){
  return(cunsum(c(0, sample(c(-1, 1), size = n-1, replace =TRUE))))
}

I would like to make recursive random walk function. what I did was

recursive.rwalk=function(n){
  return(random.walk(n-1) + random.walk(n))
}

but then Im getting warning message. Please help me out! Thanks

Wesley Bland
  • 8,816
  • 3
  • 44
  • 59
user3358686
  • 883
  • 2
  • 7
  • 7
  • a warning message, huh? That's bad – rawr Feb 27 '14 at 15:01
  • 1
    What warning are you getting? Note that in general, recursive functions are avoided in R. R is not optimized to handle them ([see this question](http://stackoverflow.com/questions/5273857/are-recursive-functions-used-in-r)). – Christopher Louden Feb 27 '14 at 15:02
  • 1
    what is `consum`? do you mean `cumsum`? `random.walk` takes an argument `k` and you do not use `k` in the function. Start there – rawr Feb 27 '14 at 15:03
  • a warning message : longer object length is not a multiple of shorter object length – user3358686 Feb 27 '14 at 15:04
  • -1 "random walk function with recursive. solve the problem thank you" not a real question. I understand you've made an edit but until it gets remedied, -1. – Hugh Feb 28 '14 at 03:49
  • bad question on SO. rewrite question thank you. – Dason Feb 28 '14 at 04:07
  • What are you hoping the value of `recursive.rwalk(5)` be? For instance, do you want it to be a single value (the final position after a 5 unit walk), or a vector showing the route of the walk? Is the walk meant to be a walk of length 5 followed by a walk of length 4, or a walk of length 4 followed by a walk of length 1? – Hugh Feb 28 '14 at 04:26

2 Answers2

2

You are trying to add two vectors of different lengths: n-1 and n in this line: random.walk(n-1) + random.walk(n). R is warning you that the first element of the first vector is added to the last element of the second vector (value recycling).

Christopher Louden
  • 7,540
  • 2
  • 26
  • 29
0

Altough it's obviously not a good idea to calculate a random walk recursively in R, here is how you would do that. First of all you have to recursively call the recursive.rwalk function, not the random.walk function. Next, you still need to sample each step of the way. And finally you need to tell the function when to stop recursively calling itself. Here's one way that will work:

recursive.rwalk=function(n){
  if (n==0) return(0)
  rw <- recursive.rwalk(n-1)
  return(c(rw, rw[n-1]+sample(c(-1,1), 1)))
}
set.seed(123)
recursive.rwalk(5)
## [1] 0 1 0 1 2
shadow
  • 21,823
  • 4
  • 63
  • 77