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