如何按r中的因子计算间隔天数

发布于 2025-01-27 08:46:38 字数 639 浏览 4 评论 0原文

我有这个数据集,我想计算每个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嘿哥们儿 2025-02-03 08:46:38
df %>% 
  group_by(id) %>% 
  summarise(days=difftime(max(date),min(date), units = "day"))

df %>% 
  group_by(id) %>% 
  summarise(days=difftime(max(date),min(date), units = "day"))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文