如何按r中的因子计算间隔天数
我有这个数据集,我想计算每个ID的持续时间。我该怎么做?例如,如果日期从26日跳到30日,我也希望那些日子也被计算在内。我尝试使用summarize()
和gengregate()
,但没有成功。
library(lubridate)
library(dplyr)
id <- as.factor(c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"))
date <- ymd_hms(c("2017-11-26 09:00:00", "2017-11-26 09:05:00", "2017-11-30 09:00:00",
"2017-11-30 09:05:00", "2017-12-02 09:00:00", "2017-11-26 09:00:00",
"2017-11-26 09:05:00", "2017-11-30 09:00:00", "2017-11-30 09:05:00", "2017-12-04 09:00:00"))
df <- tibble(id,date)
预期输出示例
> output
id days
A 7
B 9
I have this dataset and I would like to calculate the duration of days for each ID. How can I do this? If the date jumped from the 26th to the 30th for example, I would like those days to be counted as well. I tried with summarise()
and aggregate()
but no success.
library(lubridate)
library(dplyr)
id <- as.factor(c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B"))
date <- ymd_hms(c("2017-11-26 09:00:00", "2017-11-26 09:05:00", "2017-11-30 09:00:00",
"2017-11-30 09:05:00", "2017-12-02 09:00:00", "2017-11-26 09:00:00",
"2017-11-26 09:05:00", "2017-11-30 09:00:00", "2017-11-30 09:05:00", "2017-12-04 09:00:00"))
df <- tibble(id,date)
Expected output example
> output
id days
A 7
B 9
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)