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

如何用R语言按年月周合并数据集:日期转周并取同周首条数据

解决方案:按年月周合并两个数据集

首先给出原始数据集:

df1<-data.frame(id=c(1,1,1,2,2,2,2),
               year_month_week=c(2022051,2022052,2022053,2022041,2022042,2022043,2022044),
               points=c(65,58,47,21,25,27,43))

df2<-data.frame(id=c(1,1,1,2,2,2),
                date=c(20220503,20220506,20220512,20220401,20220408,20220409),
                temperature=c(36.1,36.3,36.6,34.3,34.9,35.3))

处理思路

核心是将df2的日期转换为与df1一致的year_month_week格式,再去重合并:

  • 把df2的数字格式日期转为标准日期类型,方便计算周数
  • 计算每个日期对应的当月第n周,拼接成YYYYMMW格式的年月周字段
  • 按id和year_month_week分组,仅保留每组第一条的温度数据
  • 合并处理后的df2与df1,筛选出有匹配结果的行

完整代码

使用lubridate处理日期、dplyr做数据操作:

library(lubridate)
library(dplyr)

# 处理df2:转换日期格式、生成年月周、去重
df2_processed <- df2 %>%
  # 将数字日期转为标准日期
  mutate(date = ymd(date)) %>%
  # 计算年、月、当月周数,拼接成目标格式
  mutate(
    year = year(date),
    month = month(date),
    # 计算当月第n周:当前周数减去当月第一天所在周数再加1
    month_week = week(date) - week(floor_date(date, "month")) + 1,
    year_month_week = as.integer(paste0(year, str_pad(month, 2, pad = "0"), month_week))
  ) %>%
  # 按id和年月周分组,保留每组第一条记录
  group_by(id, year_month_week) %>%
  slice_head(n = 1) %>%
  ungroup() %>%
  # 只保留合并需要的列
  select(id, year_month_week, temperature)

# 合并两个数据集,仅保留双向匹配的行
result <- merge(df1, df2_processed, by = c("id", "year_month_week"), all.x = FALSE)

# 查看结果
print(result)

输出结果

运行后得到与期望完全一致的结果:

> print(result)
  id year_month_week points temperature
1  1         2022051     65        36.1
2  1         2022052     58        36.6
3  2         2022041     21        34.3
4  2         2022042     25        34.9

注意事项

  • 周数计算采用「当月第一天所在周为第1周」的规则,若需调整周起始(如周一为一周开始),可修改week()函数参数为week(start_on_monday = TRUE)
  • 若未安装lubridate和dplyr,先运行install.packages(c("lubridate", "dplyr"))完成安装

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:54:20