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

如何用dplyr将多组lag/lead值合并到同一新列并展开行?

解决方案

首先加载所需工具包:

library(dplyr)
library(tidyr)

你的原始数据:

df <- structure(list(date = structure(c(19662, 19663, 19664, 19665, 19666), class = "Date"), 
                     tmax = c(12, 13, 12, 11, 15)), 
                class = "data.frame", row.names = c(NA, -5L))

实现需求的代码:

result <- df %>%
  rowwise() %>%
  # 生成当前日期的前两天、当天、后两天的日期序列
  mutate(climate_dates = list(seq(date - 2, date + 2, by = "day"))) %>%
  # 将列表列展开为多行
  unnest(climate_dates) %>%
  # 匹配对应日期的tmax值,无数据则填充NA
  left_join(df, by = c("climate_dates" = "date"), suffix = c("", "_climate")) %>%
  # 保留目标列并按日期排序
  select(date, tmax, tmax_climate) %>%
  arrange(date)

运行后输出结果与你提供的示例完全一致:每个日期对应5行数据,tmax_climate列会自动填充对应日期的tmax值,不存在的日期则显示NA,值的顺序符合你的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:52:51