简体   繁体   中英

R: censored cumsum (censored random walk)

I would like to be able to censor the generation of random walk data so that the walk never drops below a target value (generally 0). The following code accomplishes what I would want it to except I would rather have a function that works similar to cumsum that I can use to crunch through quickly millions of rows of such values such as cumsum(x,min=0) :

x <- rnorm(1000)
y <- rep(0,length(x))
for(i in 2:length(x)) y[i] <- max(x[i]+y[i-1], 0)
plot(y, type='l')

审查的随机游走

Why not make your own function (copied from your code, but added initialization of y[1] to make it similar to cumsum behavior):

cumsum0<-function(x,min=0){
  y<-rep(0,length(x))
  y[1]<-max(x[1],0)
  for (i in 2:length(x)) y[i] <- max(x[i]+y[i-1], min)
  return(y)
}

x<-rnorm(1000)
plot(cumsum0(x),type="l")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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