去年同期销售

时间:2015-11-07 18:06:02

标签: r

我有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 个答案:

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