You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言使用dplyr在两日期区间按年月间隔新增行扩展分组数据

R语言按日期范围生成分行年月数据的实现方法

你可以结合dplyr、lubridate、tidyr三个工具包实现需求,完整代码如下:

首先加载依赖包:

library(dplyr)
library(lubridate)
library(tidyr)

核心处理逻辑:

result <- df %>%
  # 将原始字符型日期转为标准日期格式,提取起始年月作为输出的start_date列
  mutate(across(c(start_date, end_date), ymd),
         start_date = format(start_date, "%Y-%m")) %>%
  # 按行生成该记录覆盖的所有年月序列
  rowwise() %>%
  mutate(year_month = list(
    seq.Date(from = floor_date(ym(start_date), unit = "month"),
             to = floor_date(end_date, unit = "month"),
             by = "month") %>% 
      format("%Y-%m")
  )) %>%
  # 拆分年月序列生成分行
  unnest(year_month) %>%
  # 按要求保留对应列
  select(id, start_date, year_month)

验证输出示例(以id=1为例):

result %>% filter(id == "1")
#> # A tibble: 10 × 3
#>   id    start_date year_month
#>   <chr> <chr>      <chr>     
#> 1 1     2021-01    2021-01   
#> 2 1     2021-01    2021-02   
#> 3 1     2021-01    2021-03   
#> 4 1     2021-01    2021-04   
#> 5 1     2021-01    2021-05   
#> 6 1     2021-01    2021-06   
#> 7 1     2021-01    2021-07   
#> 8 1     2021-01    2021-08   
#> 9 1     2021-01    2021-09   
#> 10 1    2021-01    2021-10

内容的提问来源于stack exchange,提问作者Sasha Poda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:54:04