如何将R dataframe中的月度数值替换为年度均值且保留原有列结构
实现方法
核心逻辑:无需做长宽表转换,按年份分组后直接对数值列做均值替换即可完全保留原有表结构,以下提供两种常用实现方案:
方案1:tidyverse实现(写法灵活,适合多列批量处理)
library(dplyr) library(lubridate) df_result <- df %>% mutate(year = year(ymd(date))) %>% # 从日期列提取年份 group_by(year) %>% # 按年份分组 # 批量替换所有数值列为对应年份均值,如需指定仅替换hfgf、lmo可改为across(c(hfgf, lmo), ~mean(.x)) mutate(across(where(is.numeric), ~mean(.x, na.rm = TRUE))) %>% ungroup() %>% select(-year) # 删除临时生成的年份列,完全还原原有列结构
处理后数据样例:
| date | hfgf | lmo |
|---|---|---|
| 2019-01-01 | 0.6766667 | 3.466667 |
| 2019-02-01 | 0.6766667 | 3.466667 |
| 2019-03-01 | 0.6766667 | 3.466667 |
| 2020-04-01 | 0.3150000 | 3.750000 |
| 2020-05-01 | 0.3150000 | 3.750000 |
| 2021-06-01 | 3.9700000 | 9.500000 |
方案2:base R实现(无需加载第三方包)
# 提取年份 df$year <- format(as.Date(df$date), "%Y") # 按年份分组替换指定列的数值为年度均值 df[c("hfgf", "lmo")] <- lapply(c("hfgf", "lmo"), function(col) { ave(df[[col]], df$year, FUN = function(x) mean(x, na.rm = TRUE)) }) # 删除临时年份列 df$year <- NULL
内容的提问来源于stack exchange,提问作者bic ton
相关产品推荐
相关产品推荐

