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

如何在R中用lag/lead计算chla变量的连续两月中位数

用dplyr计算连续两月chla中位数的解决方案

步骤说明

  1. 先按月份排序数据集,确保lead()能正确匹配下一月数据
  2. 用lead()提取下一月的chla值
  3. 按行计算当前月与下一月chla的中位数,若下一月无数据(NA),直接返回当前月chla值

示例数据集

假设你的数据集结构如下:

library(tibble)

df <- tibble(
  month = 5:10,  # 仅5-10月有样本
  chla = c(1.2, 3.4, 2.1, 4.5, 3.2, 2.8)
)

dplyr实现代码

方法一:用rowwise()按行计算

library(dplyr)

df_processed <- df %>%
  arrange(month) %>%
  mutate(chla_next = lead(chla)) %>%
  rowwise() %>%
  mutate(chla_2month_median = median(c(chla, chla_next), na.rm = TRUE)) %>%
  ungroup()

方法二:用purrr::pmap_dbl()(无需rowwise)

library(dplyr)
library(purrr)

df_processed <- df %>%
  arrange(month) %>%
  mutate(
    chla_next = lead(chla),
    chla_2month_median = pmap_dbl(list(chla, chla_next), ~ median(c(..1, ..2), na.rm = TRUE))
  )

输出结果

运行后得到的数据集如下:

# # A tibble: 6 × 4
#   month  chla chla_next chla_2month_median
#   <int> <dbl>     <dbl>              <dbl>
# 1     5   1.2       3.4                2.3
# 2     6   3.4       2.1                2.75
# 3     7   2.1       4.5                3.3
# 4     8   4.5       3.2                3.85
# 5     9   3.2       2.8                3
# 6    10   2.8      NA                  2.8

扩展说明

如果数据包含分组(如不同监测站点),只需在arrange()前添加group_by(分组变量),即可按分组计算各站点的连续两月中位数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 03:22:41