简体   繁体   English

R中大于0的值的随机游动总和

[英]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) 我想编写一个函数,使rwabovex是大于0的S值的总和。(我的S是随机游动仿真)

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). 例如:如果n = 4且S值为-1、2、1、0,则“之上”应等于3(因为2和1大于0)。

Thanks! 谢谢!

First, you're not using vectorization to compute S , which will make the procedure slow for large n . 首先,您没有使用向量化来计算S ,这会使n大的过程变慢。 You can vectorize using cumsum . 您可以使用cumsum进行矢量化。 Secondly, you can use sum to compute the sum of values in S greater than 0: 其次,可以使用sum来计算S大于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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM