Random walk sum of values greater than 0 in R

I want to write a function such that rwabovex is the sum of the values of S that are greater than 0. (My S is a random walk simulation)

Here's what I have so far but I'm not getting the right output. Can you please help?

rwabovex=function(n){
  if (n <= 0) {
    return(cat("n must be greater than 0"))
  } else {
    S=numeric(n)
    S[1] = 0
    above = 0
    for(i in 2:n) {
      step=c(1, -1)
      S[i]=S[i-1]+sample(step, 1, prob = c(0.5, 0.5), replace = TRUE)
      if (S[i] > 0) {   
        above = above + S[i]
      }
      print(above)
    }
  }
}

For example: if n=4 and the S values are -1, 2, 1, 0 then "above" should equal to 3 (since 2 and 1 are greater than 0).

Thanks!

Answers


First, you're not using vectorization to compute S, which will make the procedure slow for large n. You can vectorize using cumsum. Secondly, you can use sum to compute the sum of values in S greater than 0:

rwabovex = function(n) {
  step = c(1, -1)
  S = c(0, cumsum(sample(step, n-1, prob=c(.5, .5), replace=T)))
  print(S)
  return(sum(S[S > 0]))
}

set.seed(144)
rwabovex(10)
#  [1]  0 -1  0  1  2  1  2  1  2  1
# [1] 10

Need Your Help

ANT job to invoke JDeveloper to create EAR file with specified deploy file

ant jdeveloper

I was asked about the possibility of creating an ANT script that could be use to copy property files (associated to target environment), create an EAR file (perhaps using JDeveloper deploy file), and

Matrix multiplication with iterator dependency - NumPy

python arrays performance numpy multiplication

Sometime back this question (now deleted but 10K+ rep users can still view it) was posted. It looked interesting to me and I learnt something new there while trying to solve it and I thought that's...