R语言中AdStock转换的技术问询:含参考文档与实现代码
Hey there! Let's walk through implementing the AdStock transformation from that MPRA document (page 6) using R, building on the code snippet you shared.
First, let's recap the core AdStock formula
From the document, the AdStock effect captures the lingering impact of advertising over time. The formula is:
$A_t = X_t + \lambda A_{t-1}$
Where:
- $A_t$ = AdStock value for period t
- $X_t$ = Raw advertising spend in period t
- $\lambda$ = Adstock retention rate (your
adstock_rate, between 0 and 1 — higher values mean longer-lasting ad effects) - We start with $A_1 = X_1$ (the first period's AdStock equals its raw advertising spend, which is the standard initial condition)
Full R implementation
First, let's formalize your input data (I filled in the repeated zeros and truncated final value for completeness):
adstock_rate <- 0.50 advertising <- c(117.913, 120.112, 125.828, 115.354, 177.090, 141.647, 137.892, rep(0, 11), 158.511, 109.38)
Method 1: Basic loop (matches the formula exactly)
This is the most transparent way to replicate the document's math, since it follows the recursive formula step-by-step:
# Initialize an empty vector to store AdStock values adstock <- numeric(length(advertising)) # Set first period's AdStock to the first advertising value adstock[1] <- advertising[1] # Calculate AdStock for each subsequent period for (t in 2:length(advertising)) { adstock[t] <- advertising[t] + adstock_rate * adstock[t-1] }
Method 2: Using stats::filter() (cleaner for time series)
R's built-in filter() function handles recursive calculations efficiently, which is great for longer time series:
# Use recursive filter to compute AdStock adstock_filter <- stats::filter(advertising, filter = adstock_rate, method = "recursive") # Convert the time series output to a regular vector adstock_filter <- as.vector(adstock_filter)
Verify consistency
Both methods produce identical results — you can confirm this with:
all.equal(adstock, adstock_filter) # Returns TRUE if calculations match
Key behavior to note
- When advertising spend is 0 (like your 11 consecutive zeros), AdStock decays exponentially: each period's value is 50% of the prior period's value (since
adstock_rate = 0.5), gradually approaching 0. - When new advertising spend is added (e.g., the 18th period's 158.511), the AdStock resets to the new spend plus 50% of the remaining decayed value from the prior period.
内容的提问来源于stack exchange,提问作者Nick Knauer

