2017-03-16 2 views
0

함수를 사용하여 변수 이름을 바꾸려면 dplyr :: left_join을 사용하고 싶습니다.left_join (dplyr) 함수 사용

# increment 'startdate' by 'shift'-months 
library(lubridate) 
monthinc<-function(startdate,shift) { 
    y<-year(startdate); m<-month(startdate); d<-day(startdate) 
    y<-y+(m+shift-1) %/% 12 
    m<-ifelse(((m+shift) %% 12)==0,12,(m+shift) %% 12) 
    as.Date(paste0(y,"-",m,"-",d)) 
} 

이것은 내가 내 자신에있어 얼마나 멀리입니다 :

library(dplyr) 
t<-tibble(Product=rep(c('A','B','C'),each=15), 
     Date=rep(seq(as.Date("2010-01-01"),by="month",length.out=15),times=3), 
     Qty=round(rnorm(45,100,10),1)) 

이 내가 사용하고자하는 기능은 다음과 같습니다

데이터입니다

left_join(t,t,by=c("Product","Date")) 

# left_join should have the effect of this SQL-statement: 
# ------------------------------------------------------- 
# select d1.*,d2.Qty As Lag1_Qty 
# from t d1 
# left join t d2 
# on d1.Product=d2.Product 
#  AND d1.Date=monthinc(d2.Date,-1) 

left_join을 사용하여 위의 SQL 문을 어떻게 재현 할 수 있습니까? 그냥 왼쪽은`* _join`의 모든 기능에 의해

t <- t %>% mutate(monthinc = monthinc(Date,-1)) 

left_join(t,t,by=c("Product","Date"="monthinc")) 
+1

AFAIK이 기능이 지원되지 않습니다에 합류하기 전에 열로 추가 할 경우 – nrussell

+0

나는 그것을 가지고 있다고 생각한다. 감사. my.lag <-1 t.new <-left_join (t, 변환 마법 (t, 제품, 날짜 = monthinc (날짜, my.lag) = C로 Qty_Lag = 수량) (" 제품 ","날짜 ")) 보기 (t.new) –

답변

1

은 단순해야한다.