考虑以下形式的数据框
idnum start end
1993.1 17 1993-01-01 1993-12-31
1993.2 17 1993-01-01 1993-12-31
1993.3 17 1993-01-01 1993-12-31
用start
和end
为类型的Date
$ idnum : int 17 17 17 17 27 27
$ start : Date, format: "1993-01-01" "1993-01-01" "1993-01-01" "1993-01-01" ...
$ end : Date, format: "1993-12-31" "1993-12-31" "1993-12-31" "1993-12-31" ...
我想创建一个新的数据框,取而代之的是在start
和之间end
(包括边界)的每个月的每一行的每月观测值:
期望的输出
idnum month
17 1993-01-01
17 1993-02-01
17 1993-03-01
...
17 1993-11-01
17 1993-12-01
我不确定month
应该采用哪种格式,我有时会希望按分组idnum
,month
以便对其余数据集进行回归。
到目前为止,对于每一行,seq(from=test[1,'start'], to=test[1, 'end'], by='1 month')
它给我正确的顺序-但是,一旦我尝试将其应用于整个数据帧,它将无法正常工作:
> foo <- apply(test, 1, function(x) seq(x['start'], to=x['end'], by='1 month'))
Error in to - from : non-numeric argument to binary operator
使用data.table
:
require(data.table) ## 1.9.2+
setDT(df)[ , list(idnum = idnum, month = seq(start, end, by = "month")), by = 1:nrow(df)]
# you may use dot notation as a shorthand alias of list in j:
setDT(df)[ , .(idnum = idnum, month = seq(start, end, by = "month")), by = 1:nrow(df)]
setDT
转换df
为data.table
。然后,为每一行by = 1:nrow(df)
创建idnum
并month
根据需要创建。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句