Marta
Marta

Reputation: 3843

Generate a sequence by formula with R

I want to generate a sequence:

X_n= |X_{n-1} - epsilon_n|,

where epsilon_n has an exponential distribution.

For example

epsilon <- rexp(100, rate = 0.3)

Upvotes: 0

Views: 449

Answers (2)

Roland
Roland

Reputation: 132706

Use Reduce:

X0 <- 10
set.seed(42)
epsilon<-rexp(100, rate = 0.3)
eps <- c(X0, epsilon)

X <- Reduce(function(x, y) abs(x-y), eps, accumulate = TRUE)

plot(X)

enter image description here

Upvotes: 4

nrussell
nrussell

Reputation: 18602

## n is length of the sequence, X0 is initial value, 
## default exponential rate is 0.3
xSeq <- function(n,X0,rate=0.3){
  vOut <- rep(0,n)
  vOut[1] <- X0
  eSeq <- rexp(n-1,rate)
  for(i in 2:n){
    vOut[i] <- abs(vOut[i-1]-eSeq[i-1])
    vOut
  }
  return(vOut)
}

Upvotes: 1

Related Questions