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