2012-12-06 3 views
2
나는 현재 감쇄율 Y의 붕괴 (adstock) 함수를 만들려면 다음 코드를 사용하고

에 풀 모델 (adstock) :붕괴 기능 R

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

그리고이 원하는 결과를 제공합니다.

그러나 각 영역이 함께 그룹화되고 시간순으로 실행되도록 풀링 된 데이터 집합이있는 경우 두 번째 영역의 시작 부분에는 첫 번째 끝 부분에서 부작용이 있습니다. 제 3 지역 등과 마찬가지로 ...

(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) 

새로운 기능은 각 지역의 감쇠 기능을 실행해야합니다. 따라서 2012 년 1 월 11 일, "West"지역에 대한 행은 항상 0이어야합니다.

+1

안녕하십니까, 데이터 예제를 재현 할 수 있습니까? – agstudy

+0

죄송합니다. 데이터 예제를 업로드하는 가장 쉬운 방법은 무엇입니까? 예제 테이블이 제대로 나타나지 않습니다. – user1882017

+0

이 위대한 링크를 볼 수 있습니다 http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – agstudy

답변

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)