假设我们有以下数据框:
ShippedDate OrderID Subtotal
1 1996-07-16 00:00:00 10248 440.00
2 1996-07-10 00:00:00 10249 1863.40
...
25 1996-08-06 00:00:00 10272 1456.00
26 1996-08-12 00:00:00 10273 2142.40
...
51 1996-09-11 00:00:00 10298 3127.00
52 1996-09-13 00:00:00 10299 349.50
...
78 1996-10-14 00:00:00 10325 1497.00
79 1996-10-14 00:00:00 10326 982.00
80 1996-10-14 00:00:00 10327 2262.50
81 1996-10-17 00:00:00 10328 1168.00
etc
1 1996-07-16 00:00:00 10248 440.00 2 1996-08-12 00:00:00 10273 2142.40 3 1996-09-13 00:00:00 10299 349.50 4 1996-10-14 00:00:00 10327 2262.50
1 1996-07 2303.4 2 1996-08 3598.4 3 1996-09 3476.5 4 1996-10 5909.5
我建议您year-month
一次创建一个变量,然后在所有其他操作中使用该变量,以避免一遍又一遍地重新计算它。
这是一种可能的data.table
方法
创建变量
library(data.table)
setDT(df)[, YearMonth := paste0(year(ShippedDate), "-", month(ShippedDate))]
从每年的月份中随机抽样
df[, .SD[sample(seq_len(.N), 1)], by=YearMonth]
# YearMonth ShippedDate OrderID Subtotal
# 1: 1996-7 1996-07-16 00:00:00 10248 440.0
# 2: 1996-8 1996-08-12 00:00:00 10273 2142.4
# 3: 1996-9 1996-09-11 00:00:00 10298 3127.0
# 4: 1996-10 1996-10-14 00:00:00 10326 982.0
每年每月的总和
df[, sum(Subtotal), by=YearMonth]
# YearMonth V1
# 1: 1996-7 2303.4
# 2: 1996-8 3598.4
# 3: 1996-9 3476.5
# 4: 1996-10 5909.5
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句