R:计算未来特定时间内特定事件的发生次数

编程入门 行业动态 更新时间:2024-10-13 20:21:31
本文介绍了R:计算未来特定时间内特定事件的发生次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的简化数据如下所示:

my simplified data looks like this:

set.seed(1453); x = sample(0:1, 10, TRUE) date = c('2016-01-01', '2016-01-05', '2016-01-07', '2016-01-12', '2016-01-16', '2016-01-20', '2016-01-20', '2016-01-25', '2016-01-26', '2016-01-31') df = data.frame(x, date = as.Date(date)) df x date 1 2016-01-01 0 2016-01-05 1 2016-01-07 0 2016-01-12 0 2016-01-16 1 2016-01-20 1 2016-01-20 0 2016-01-25 0 2016-01-26 1 2016-01-31

我想计算 x ==的出现次数1 在指定的时间段内,例如从当前日期起14天和30天(但不包括当前条目,如果它是 x == 1 ,所需的输出将如下所示:

I'd like to calculate the number of occurrences for x == 1 within a specified time period, e.g. 14 and 30 days from the current date (but excluding the current entry, if it is x == 1. The desired output would look like this:

solution x date x_plus14 x_plus30 1 2016-01-01 1 3 0 2016-01-05 1 4 1 2016-01-07 2 3 0 2016-01-12 2 3 0 2016-01-16 2 3 1 2016-01-20 2 2 1 2016-01-20 1 1 0 2016-01-25 1 1 0 2016-01-26 1 1 1 2016-01-31 0 0

理想情况下,我希望这是在 dplyr 但是它不是必须的任何想法如何实现这一点非常感谢您的帮助!

Ideally, I'd like this to be in dplyr, but it is not a must. Any ideas how to achieve this? Thanks a lot for your help!

推荐答案

添加另一种方法在 findInterval :

cs = cumsum(df$x) # cumulative number of occurences data.frame(df, plus14 = cs[findInterval(df$date + 14, df$date, left.open = TRUE)] - cs, plus30 = cs[findInterval(df$date + 30, df$date, left.open = TRUE)] - cs) # x date plus14 plus30 #1 1 2016-01-01 1 3 #2 0 2016-01-05 1 4 #3 1 2016-01-07 2 3 #4 0 2016-01-12 2 3 #5 0 2016-01-16 2 3 #6 1 2016-01-20 2 2 #7 1 2016-01-20 1 1 #8 0 2016-01-25 1 1 #9 0 2016-01-26 1 1 #10 1 2016-01-31 0 0

更多推荐

R:计算未来特定时间内特定事件的发生次数

本文发布于:2023-11-27 13:30:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638276.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:次数   发生   事件   未来   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!