有滞后的累计和 [英] Cumulative sum with lag

查看:18
本文介绍了有滞后的累计和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的数据集,看起来像这样简化:

I have a very large dataset that looks simplified like this:

row.    member_id   entry_id    comment_count   timestamp
1       1            a              4           2008-06-09 12:41:00
2       1            b              1           2008-07-14 18:41:00
3       1            c              3           2008-07-17 15:40:00
4       2            d              12          2008-06-09 12:41:00
5       2            e              50          2008-09-18 10:22:00
6       3            f              0           2008-10-03 13:36:00

我可以使用以下代码汇总计数:

I can aggregate the counts with the following code:

transform(df, aggregated_count = ave(comment_count, member_id, FUN = cumsum))

但我希望累积数据滞后 1,或者我希望 cumsum 忽略当前行.结果应该是:

But I want a lag of 1 in the cumulated data, or I want cumsum to ignore the current row. The result should be:

row.    member_id   entry_id     comment_count  timestamp             previous_comments
1       1            a              4           2008-06-09 12:41:00        0
2       1            b              1           2008-07-14 18:41:00        4
3       1            c              3           2008-07-17 15:40:00        5
4       2            d              12          2008-06-09 12:41:00        0
5       2            e              50          2008-09-18 10:22:00        12
6       3            f              0           2008-10-03 13:36:00        0

知道如何在 R 中做到这一点?甚至可能有大于 1 的延迟?

Some idea how I can do this in R? Maybe even with a lag bigger than 1 ?

再现性数据:

# dput(df)
structure(list(member_id = c(1L, 1L, 1L, 2L, 2L, 3L), entry_id = c("a", 
"b", "c", "d", "e", "f"), comment_count = c(4L, 1L, 3L, 12L, 
50L, 0L), timestamp = c("2008-06-09 12:41:00", "2008-07-14 18:41:00", 
"2008-07-17 15:40:00", "2008-06-09 12:41:00", "2008-09-18 10:22:00", 
"2008-10-03 13:36:00")), .Names = c("member_id", "entry_id", 
"comment_count", "timestamp"), row.names = c("1", "2", "3", "4", 
"5", "6"), class = "data.frame")

推荐答案

第一个元素可以使用0,最后一个元素可以使用head(, -1)

You can use 0 for the first element, and remove the last element using head(, -1)

transform(df, previous_comments=ave(comment_count, member_id, 
          FUN = function(x) cumsum(c(0, head(x, -1)))))
#  member_id entry_id comment_count           timestamp previous_comments
#1         1        a             4 2008-06-09 12:41:00                 0
#2         1        b             1 2008-07-14 18:41:00                 4
#3         1        c             3 2008-07-17 15:40:00                 5
#4         2        d            12 2008-06-09 12:41:00                 0
#5         2        e            50 2008-09-18 10:22:00                12
#6         3        f             0 2008-10-03 13:36:00                 0

这篇关于有滞后的累计和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆