0

I am trying to create the adstock effect for some variable (adstock is defined as value of the previous observation + value of previous observation*adstock rate). I have a table abc that has two columns: GEOG (A, B ,C) and GRPs (1 to 6) for a total of 18 observations. I would like to create a variable b by taking the first obs of the first GEOG and adstocking it by say .5. Then when I get to the first obs of the second GEOG, reinitialize it=to GRPs and do it again. I created a code that works really well with only one geography. But I cannot figure out how to do it BY geography. Coming from a different statistical language, I am still wrapping my head around the way R works. Can anyone help? Thanks in advance. Here is the code that works for one GOEG:

 rate1=.5  
 rate2=0
for (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    a   b
A   1   1
A   2   2.5
A   3   4.25
A   4   6.125
A   5   8.0625
A   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
cesco
  • 63
  • 1
  • 1
  • 4
  • Please provide a reproducible data example and desired result. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Pierre Lapointe Jul 02 '17 at 23:04

2 Answers2

0
transfo <- function(df, rate1 = 0.5, rate2 = 0) {

  b <- df[["a"]]

  for (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 at http://r4ds.had.co.nz/many-models.html.

F. Privé
  • 11,423
  • 2
  • 27
  • 78
0

You can use the stats::filter function and dplyr.

library(tidyverse)

df %>%
  group_by(GEOG) %>%
  mutate(adstock = stats::filter(x=abc, filter=0.5, method="recursive")) %>%
  ungroup()
sonicking
  • 16
  • 1