0
我想使用函數dplyr :: left_join並重命名一個變量。left_join(dplyr)使用函數
這是數據:
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))
這是我想使用的功能:
# 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))
}
這是我對我自己有多遠了:
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語句?
AFAIK不支持此功能前將其添加爲一列。 – nrussell
我想我已經明白了。謝謝。 my.lag <-1 t.new <-left_join(T, 蛻變(T, 產品, 日期= monthinc(日期,my.lag) Qty_Lag =數量),通過 = C(」產品「,」日期「)) 查看(t.new) –