我试图计算df1中的行数,其中包含事件的日期,

df1 = data.frame(date = c("2021-07-31", "2021-08-01", "2021-08-12", "2021-08-14"))

在df2的开始和结束日期内,

df2 = data.frame(Id = c(1,2), 
                 Start = c("2021-06-01", "2021-08-01"), 
                 End = c("2021-08-15", "2021-09-15"))

在本例中,输出如下所示

  Id      Start        End Count
1  1 2021-06-01 2021-08-15     3
2  2 2021-08-01 2021-09-15     3

我试过How to get the number of counts between two dates in R?How to get the number of counts between two dates in R?个类似的例子

如有任何帮助或建议,将不胜感激.非常感谢.

推荐答案

请注意:Id 1在您的预期输出中应该是4吗?

您可以将数据设置为group_by,然后将interval的日期相加,如下所示:

df1 = data.frame(date = c("2021-07-31", "2021-08-01", "2021-08-12", "2021-08-14"))
df2 = data.frame(Id = c(1,2), 
                 Start = c("2021-06-01", "2021-08-01"), 
                 End = c("2021-08-15", "2021-09-15"))

library(dplyr)
library(lubridate)
df2 %>%
  group_by(Id) %>%
  mutate(Count = sum(as_date(df1$date) %within% lubridate::interval(Start, End)))
#> # A tibble: 2 × 4
#> # Groups:   Id [2]
#>      Id Start      End        Count
#>   <dbl> <chr>      <chr>      <int>
#> 1     1 2021-06-01 2021-08-15     4
#> 2     2 2021-08-01 2021-09-15     3

reprex package(v2.0.1)于2022-07-12创建

R相关问答推荐

使用ggcorrplot在相关性矩阵上标注supertitle和index标签

基于多列将值链接到NA

在R中为马赛克图中的每个字段着色

如何在R forestplot中为多条垂直线分配唯一的 colored颜色 ?

基于R中的间隔扩展数据集行

QY数据的处理:如何定义QY因素的水平

随机森林的带Shap值的蜂群图

如何使用字符串从重复的模式中提取多个数字?

R代码,用于在线条图下显示观测表

避免在图例中显示VLINS组

变异以按组从其他列创建具有最大和最小值的新列

如何将EC50值绘制在R中的剂量-react 曲线上?

R中的Desolve:返回的导数数错误

R try Catch in the loop-跳过缺少的值并创建一个DF,显示跳过的内容

排序R矩阵的行和列

以R表示的NaN值的IS.NA状态

如何在矩阵图中按标准对数据进行分组以绘制矩阵

在R中使用ggraph包排列和着色圆

在分面的ggplot2条形图中对条形图进行排序,并省略每组未使用的系数级别

为各个小节生成单独的选项卡