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

在R中按年月周规则合并数据集并处理缺失值

按年月周合并R数据集解决方案

需求说明

现有两个数据集df1和df2,df1用year_month_week(格式YYYYMMW,如2022051代表2022年5月第1周)标识时间,df2用date(格式YYYYMMDD)标识时间。需要按id+year_month_week将两者合并:同一id和周内有多个温度值时取第一个,无对应数据则填充NA,最终结果行数与df1完全一致。

实现步骤

1. 加载依赖包

处理日期和数据操作需用到lubridate和dplyr,首次使用需先安装:

install.packages(c("lubridate", "dplyr"))
library(lubridate)
library(dplyr)

2. 转换df2的日期格式并提取年月周

将df2的数字格式日期转为标准日期类型,计算该日期所属的当月周数,再拼接成与df1一致的year_month_week格式,最后按分组取首个温度值:

df2_processed <- df2 %>%
  mutate(
    # 把数字date转为标准日期
    date = ymd(date),
    # 提取年、月
    year = year(date),
    month = month(date),
    # 计算当月第几周:当月天数除以7后向上取整
    week_in_month = ceiling(day(date)/7),
    # 拼接成YYYYMMW数值格式
    year_month_week = as.numeric(paste0(year, sprintf("%02d", month), week_in_month))
  ) %>%
  # 按id和年月周分组,保留每组第一条数据
  group_by(id, year_month_week) %>%
  slice(1) %>%
  ungroup() %>%
  # 只保留合并所需列
  select(id, year_month_week, temperature)

3. 合并数据集

用left_join确保结果行数与df1一致,无匹配数据的位置自动填充NA:

final_df <- df1 %>%
  left_join(df2_processed, by = c("id", "year_month_week"))

4. 验证结果

运行代码查看最终输出:

print(final_df)

输出与预期完全一致:

id year_month_week points temperature
1  1         2022051     65        36.1
2  1         2022052     58        36.6
3  1         2022053     47          NA
4  2         2022041     21        34.3
5  2         2022042     25        34.9
6  2         2022043     27          NA
7  2         2022044     43          NA

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 04:24:13