Search code examples
rformuladifferential-equations

How to create a formula that depends on the value of another formula - R


enter image description here

H2 = 0

H3 - H999 = =SQRT(EXP(G3*0,1))*NORMINV(RAND();0;1)

I2 - I999 = =$E$2+$D$2*EXP($A$2*($G2-$B$2)+$C$2)/(1+EXP($A$2*($G2-$B$2)+$C$2))+H2

Hi guys,

i created the formula obove in excel. I want to implement this one to R. Can anyone help me with this?

I already tried to do it with formula and with data.frame.

The probelm is that sigma depends on t and X(t)-1.

Can anyone help me with it?

Thanks, Max

Edit for further question: Simulation with sigma only depending on t in R

Simulation with sigma only depending on t in Excel


Solution

  • This seems to require a for loop. If the intention is the run this multiple times to get X(t), then the replications can be vectorized within the for loop:

    fXt <- function(A, B, C, D, E, delta, steps, n) {
      t <- seq(delta, by = delta, length.out = steps)
      # pre-allocate Xt and sigma
      Xt <- matrix(rep(E + D*exp(A*(t - B) + C)/(1 + exp(A*(t - B) + C)), each = n), n, steps)
      sigma <- matrix(0, n, steps)
      r <- matrix(exp(0.025)*rnorm(n*(steps - 1L)), n, steps - 1L) # sqrt(exp(0.05)) = exp(0.025)
      
      for (i in 2:steps) {
        sigma[,i] <- r[,i - 1L]*sqrt(abs(Xt[,i - 1L] - 50))
        Xt[,i] <- Xt[,i] + sigma[,i]
      }
      
      t(Xt)
    }
    

    Call it like so:

    Xt <- fXt(2, 5, 3, 30, 100, 0.05, 998, 100)
    

    Xt will be a matrix with 998 rows and 100 columns. Each column is a different replication.