简体   繁体   English

R在去年同一月和同一天创建新的销售列

[英]R Creating New Column of Sales Last Year Same Month and Day

Assuming I have a data table (not data frame) that has columns of Year, Month, Day, Sales, and a new column Sales Last Year (Similar to the picture below), how do I create that Sales Last Year column to grab the Sales from the same day and month but one year ago? 假设我有一个数据表(非数据框),该表具有Year,Month,Day,Sales列和一个新列Sales Last Year(类似于下图),如何创建该Sales Last Year列来获取是一年前同一天和一个月的销售额?

Data 数据

dt <- data.table(Month = rep("January", times = 3),
                 Year = 2016:2018,
                 Day = rep(1, times = 3),
                 Sales = c(5000, 1000, 2000))

Expected result 预期结果 在此处输入图片说明

Generate fake data to work with: 生成伪造数据以用于:

library(data.table)
dt <- data.table(
    day   = rep(1,3),
    month = rep(1, 3),
    year  = 2016:2018,
    sales = 1:3*500
)

A "merge" approach: 一种“合并”方法:

dtcopy <- copy(dt)
dtcopy[ , year := year + 1]
setnames(dtcopy, old="sales", new="sales_last_year")
merge(dt, dtcopy, by=c("month", "day", "year"), all.x=TRUE)

A "lag" approach: 一种“滞后”方法:

dt <- dt[order(day, month, year)]
dt[ , sales_last_year := shift(sales), by=.(day, month)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM