4

I'm trying to replicate the following formula in R:

Xt = Xt-1 * b + Zt * (1-b)

I'm using the following code

t %>% 
  mutate(x= ifelse(week == 1, z, NaN)) %>% # Initial value for the first lag
  mutate(x= ifelse(week != 1, lag(x,1 ,default = 0) * b + z, z)

But I get all NaN except from the second element.

     z      b           x
     (dbl)  (dbl)    (dbl)
1  168.895  0.9      168.8950
2   20.304  0.9      131.7472
3   14.943  0.9         NA
4   11.028  0.9         NA
5    8.295  0.9         NA
6    8.024  0.9         NA
7    6.872  0.9         NA
8    7.035  0.9         NA
9    4.399  0.9         NA
10   4.158  0.9         NA

This is fairly simple in excel but I must do it in R, Do you have any approaches?

Reproducible example:

set.seed(2)
t = data.frame(week = seq(1:52),
               z = runif(52, 0, 100),
               b = 0.2)
JJ1603
  • 586
  • 1
  • 7
  • 16
  • Just use `mutate(dat, x = lag(z) * b + z * (1 - b))`? – talat Jun 23 '16 at 14:23
  • The formula should lag x, not z. It uses previous value * b + z * (1-b). But for the formula to work, the first value should be the first "z" – JJ1603 Jun 23 '16 at 14:30
  • Run this in order: `dat <- data.frame(week = seq(1:52), z = runif(52, 0, 100), b = 0.2)` then `mutate(dat, x = lag(z) * b + z * (1 - b))`. What do you get? I don't get NaNs – talat Jun 23 '16 at 14:33
  • 2
    It works lagging (z) but for the formula to work i need to lag (x) except for the first value of x which is the first z, thanks! – JJ1603 Jun 23 '16 at 14:36
  • Do you mean `mutate(dat, x = lag(z, default = z[1]) * b + z * (1 - b))`? – talat Jun 23 '16 at 14:49
  • Yes! But it throws me an error: expecting a single value. I put two brackets but it didn't work either, any suggestion? – JJ1603 Jun 27 '16 at 14:30
  • I don't get such an error. Can you provide the code and sample data you used that reproduces the error? – talat Jun 27 '16 at 14:32
  • I added the output and updated formula. The data is confidential so i cannot post it here. – JJ1603 Jun 27 '16 at 15:19
  • I think you should just code it in a loop. If speed matters, write it in Rcpp. – Frank Jun 27 '16 at 15:35

1 Answers1

2

I found the solution running the following loop, thanks to @Frank and @docendo discimus

for (row in 2:dim(t)[1]) {
    t[row,] <- mutate(t[1:row,], x= lag(x,1) * b + z * (1 - b))[row,]
  }
JJ1603
  • 586
  • 1
  • 7
  • 16