R中的混合模型的衰变函数(adstock)

时间:2012-12-06 10:40:46

标签: r

我目前正在使用以下代码创建衰减率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/201应始终为零。

1 个答案:

答案 0 :(得分: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)