R - Adstock by group -


i trying create adstock effect variable (adstock defined value of previous observation + value of previous observation*adstock rate). have table abc has 2 columns: geog (a, b ,c) , grps (1 6) total of 18 observations. create variable b taking first obs of first geog , adstocking .5. when first obs of second geog, reinitialize it=to grps , again. created code works 1 geography. cannot figure out how geography. coming different statistical language, still wrapping head around way r works. can help? in advance. here code works 1 goeg:

 rate1=.5    rate2=0 (i in 1:nrow(abc)) {    if (i ==1)     abc[i,3] <- abc[i,2]   else if (i == 2)     #effect = impression + last week effect * decay rate     abc[i,3] <- abc[i,2] + (abc[i-1,3] * rate1)   else     #effect = impression + last week effect * decay rate     abc[i,3] <- abc[i,2] + (abc[i-1,3] * rate1) + (abc[i-2,3]*rate2)  } 

output:

geog      b   1   1   2   2.5   3   4.25   4   6.125   5   8.0625   6   10.03125 b   1   1 b   2   2.5 b   3   4.25 b   4   6.125 b   5   8.0625 c   1   1 c   2   2.5 c   3   4.25 c   4   6.125 c   5   8.0625 

transfo <- function(df, rate1 = 0.5, rate2 = 0) {    b <- df[["a"]]    (i in seq_along(b)) {      if (i == 2) {       b[i] <- b[i] + rate1 * b[i-1]     } else if (i > 2) {       b[i] <- b[i] + rate1 * b[i-1] + rate2 * b[i-2]     }   }    df[["b"]] <- b   df }  abc %>%   group_by(geog) %>%   nest() %>%   mutate(data = map(data, transfo)) %>%   unnest(data) 

learn more @ http://r4ds.had.co.nz/many-models.html.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -