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

如何用R为tibble添加两日期间的唯一月份列?

问题描述

我有如下tibble数据:

library(tibble)

tibble(site = c("a", "b", "c", "d"), 
       date = c("01/12/21", "07/06/22", "02/12/22", "30/07/23"), 
       `last date` = c("01/03/22", "07/07/22", "02/12/23", "30/07/24"))

我需要添加一列months,列出date和last date之间包含的所有唯一月份名称(每个字符串最多12个元素),最终要得到如下输出:

tibble(site = c("a", "b", "c", "d"), 
       date = c("01/12/21", "07/06/22", "02/12/22", "30/07/23"), 
       `last date` = c("01/03/22", "07/07/22", "02/12/23", "30/07/24"), 
       months = c("December, January, February, March", 
                  "June, July", 
                  "December, January, February, March, April, May, June, July, August, September, October, November", 
                  "July, August, September, October, November, December, January, February, March, April, May, June"))

我试过用seq.Date的多种方法,但都没成功。

解决方案

可以通过以下步骤实现需求:

  1. 将字符格式的日期列转换为标准日期对象,匹配日/月/年的解析格式;
  2. 按行生成首尾日期覆盖的所有月份序列;
  3. 提取月份英文全称,去重后拼接成字符串。

对应的R代码如下:

library(tibble)
library(dplyr)
library(lubridate)

# 原始数据
df <- tibble(site = c("a", "b", "c", "d"), 
             date = c("01/12/21", "07/06/22", "02/12/22", "30/07/23"), 
             `last date` = c("01/03/22", "07/07/22", "02/12/23", "30/07/24"))

# 处理逻辑
df_result <- df %>%
  # 转换日期格式为标准日期对象
  mutate(across(c(date, `last date`), dmy)) %>%
  # 按行处理每组日期
  rowwise() %>%
  mutate(
    # 生成从起始月到结束月的每月第一天序列
    month_seq = list(seq(floor_date(date, "month"), floor_date(`last date`, "month"), by = "month")),
    # 提取月份全称、去重后用逗号连接
    months = stringr::str_c(unique(month(month_seq, label = TRUE, abbr = FALSE)), collapse = ", ")
  ) %>%
  # 移除中间辅助列
  select(-month_seq) %>%
  ungroup()

# 查看结果
print(df_result)

代码细节说明

  • dmy():专门处理日/月/年格式的字符型日期转换;
  • floor_date(x, "month"):将日期向下取整到当月第一天,确保序列完整覆盖对应月份;
  • seq(..., by = "month"):生成按月递增的日期序列;
  • month(..., label = TRUE, abbr = FALSE):提取月份的英文全称而非数字;
  • rowwise():保证每一行的日期对独立处理,避免跨组干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 19:16:20