2015-11-07 119 views
-1

我有DF <-(ID,Year,Sales),我想創建第四列LastYearSale,選擇去年的銷售額。例如,如果有:去年同日銷售

ID Year Sales 

1 01/01/2015 50000 
2 01/01/2014 20000 

我想輸出是這樣的:

ID Year Sales LastYearSales 

1 01/01/2015 50000 20000 
2 01/01/2014 20000 
+1

試試'library(dplyr); DF%>%mutate(LastYearSales = lead(Sales))' – akrun

回答

0

如果您Year列不在Date類,然後將其轉換成Date類首先由

df$Year <- as.Date(df$Year, "%d/%m/%Y") 

然後你可以試用lubridate

library(lubridate) 
df$LastYearSales <- c(df[df$Year %in% (as.Date(ymd(df$Year) - years(1))), ]$Sales, NA) 
df 
# ID  Year Sales LastYearSales 
# 1 1 2015-01-01 50000  20000 
# 2 2 2014-01-01 20000   NA 
相關問題