2

我目前正在使用以下代码来创建衰减率 y 的衰减(adstock)函数:

adstock <- function(x, decay=y) filter(x, decay, method = "recursive")

这给出了预期的结果。

但是,如果我有一组数据,例如每个区域都组合在一起并按时间顺序运行,那么第二个区域的开头会从第一个区域的结尾留下衰减。与第三区域类似......

确保 (n>1) 区域的第一次观察保持等于原始值但所有后续值都应用衰减公式的最佳方法是什么?

例如:

Weeks <- c("01/01/2012","08/01/2012","15/01/2012","22/01/2012","29/01/2012","01/01/2012","08/01/2012","15/01/2012","22/01/2012","29/01/2012","01/01/2012","08/01/2012","15/01/2012","22/01/2012","29/01/2012")
Regions <- c("North","North","North","North","North","South","South","South","South","South","West","West","West","West","West")
Variable <- c(5,6,4,8,6,19,20,5,7,8,0,5,4,6,7)
exampledata <- data.frame(Weeks, Regions, Variable)

新函数应该只为每个区域运行衰减函数。因此,“西部”区域的第 11 行,01/01/2012,应始终为零。

4

1 回答 1

1

尝试以下 adstock 功能:

adstock <-function(data_vector, decay, period, pool_vector=0){  
 data2<-data_vector
 l<-length(data_vector)
#if no pool apply zero to vector
if(length(pool_vector)==1)pool_vector<-rep(0,l)
#outer loop: extract data to decay from observation i
  for( i in 1:l){
    x<-data_vector[i]
#inner loop: apply decay onto following observations after i
    for(j in 1:min(period,l)){
      #constrain decay to same pool (if data is pooled)
      if( pool_vector[i]==pool_vector[min(i+j,l)]){data2[(i+j)]<- data2[(i+j)]+(x*(1-decay)^j)}
    }
  }
#reduce lenth of edited data to equal lenth of innitial data
data2<-data2[1:l]
  return(data2)
}

如果您不使用周期衰减,只需将其设置为较大的数字(大于观察次数),因此如果您希望在示例中按周期衰减 20%:

Variable_20D<-adstock(exampledata$Variable,.2,1000,exampledata$Regions)
于 2015-04-08T15:09:34.757 回答