我有一个数据:
dt <- fread("id date Note Amount
A 2/15/2012 Keep this 10
A 5/9/2012 Keep this 30
A 5/15/2012 Keep this 50
A 8/26/2012 Keep this 10
A 11/2/2012 Keep this 10
B 4/3/2012 Keep this 5
B 7/3/2012 Keep this 5
", header = T)
id date Note Amount
1: A 2/15/2012 Keep this 10
2: A 5/9/2012 Keep this 30
3: A 5/15/2012 Keep this 50
4: A 8/26/2012 Keep this 10
5: A 11/2/2012 Keep this 10
6: B 4/3/2012 Keep this 5
7: B 7/3/2012 Keep this 5
我想要的是:
fread("id YrMonth Amount Note
A 2012-01 0 Keep this
A 2012-02 10 Keep this
A 2012-03 0 Keep this
A 2012-04 0 Keep this
A 2012-05 80 Keep this
A 2012-06 0 Keep this
A 2012-07 0 Keep this
A 2012-08 10 Keep this
A 2012-09 0 Keep this
A 2012-10 0 Keep this
A 2012-11 10 Keep this
A 2012-12 0 Keep this
B 2012-01 0 Keep this
B 2012-02 0 Keep this
B 2012-03 0 Keep this
B 2012-04 5 Keep this
B 2012-05 0 Keep this
B 2012-06 0 Keep this
B 2012-07 5 Keep this
B 2012-08 0 Keep this
B 2012-09 0 Keep this
B 2012-10 0 Keep this
B 2012-11 0 Keep this
B 2012-12 0 Keep this
", header = T)
首先,我尝试如下代码:
library(data.table)
dt[, YrMonth := ymd(paste(format(date, "%Y-%m"), 01, sep = "-"))]
但是,我不知道如何创建原始数据不包括的日期。我认为我可以先分组的想法。使用dcast
将数据从长到宽转换并设置参数fill = 0
。之后,我可以通过melt
将其切换回去。
有更好的方法可以快速找出答案吗?
谢谢。