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

如何在R中为数据框新增2013-2019列的行均值变量?

解决方案:给数据框新增每行2013-2019列的均值列

你需要的是行级计算(每行单独算均值),而summarise_at是用来做列级汇总(比如整列的均值),所以会失效。以下是几种可行的方法:

方法1:rowMeans + 列范围选择

直接用rowMeans计算指定列的行均值,配合dplyr的mutate新增列:

library(dplyr)

# 加载你提供的数据
df <- structure(list(SE_at = c("01", "02", "03", "04", "05", "06"), 
                     `2002` = c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), 
                     `2003` = c(22, 18.1, 13.5, 14.9, 11.9, 13.9), 
                     `2004` = c(17, 16, 16.9, 15, 14.3, 22), 
                     `2005` = c(15.2, 12.8, 11.3, 9.5, 12.9, 18.1), 
                     `2006` = c(16.7, 13.2, 13.5, 14.3, 13.7, 12.6), 
                     `2007` = c(5.1, 3.5, 2.8, 4.2, 4.5, 4.3), 
                     `2008` = c(5.4, 4.6, 3.8, 4.1, 4.6, 6.1), 
                     `2009` = c(5.3, 5.1, 4.4, 4.2, 4.6, 5.1), 
                     `2010` = c(7.4, 7.9, 6.7, 7.1, 6.6, 7.4), 
                     `2011` = c(12.8, 11.8, 12.7, 12.3, 11.4, 11.6), 
                     `2012` = c(10.6, 10.1, 9.2, 10.6, 10.1, 9.4), 
                     `2013` = c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), 
                     `2014` = c(6, 6.6, 5.1, 6.7, 7.3, 6.5), 
                     `2015` = c(7.4, 6.8, 6.2, 7.8, 14.6, 14.5), 
                     `2016` = c(7.5, 7.1, 6.9, 6.9, 6.4, 6.4), 
                     `2017` = c(8.4, 8.1, 8.8, 7.9, 7.6, 8.5), 
                     `2018` = c(8.8, 8.3, 7, 7.9, 8.4, 9.2), 
                     `2019` = c(6.1, 5.1, 5, 4.3, 4.2, 4.7), 
                     `2020` = c(8.3, 8.1, 7.9, 7.7, 8, 8.3), 
                     `2021` = c(17.4, 15.1, 15.5, 14, 13.2, 14.7), 
                     `2022` = c(38.7, 36.3, 37.3, 34.9, 36.2, 26.2)), 
                row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))

# 新增均值列
df <- df %>%
  mutate(mean_2013_2019 = rowMeans(select(., `2013`:`2019`), na.rm = TRUE))

方法2:用across函数(新版dplyr推荐)

across是dplyr 1.0.0+替代旧版mutate_at/summarise_at的函数,语法更统一:

df <- df %>%
  mutate(mean_2013_2019 = rowMeans(across(`2013`:`2019`), na.rm = TRUE))

方法3:正则匹配列名(适合列不连续的情况)

如果2013-2019的列不是连续排列的,可以用正则表达式匹配列名:

df <- df %>%
  mutate(mean_2013_2019 = rowMeans(across(matches("^201[3-9]$")), na.rm = TRUE))

关键说明

  • na.rm = TRUE:忽略列中的NA值(你的2013列全为NA,必须开启这个参数才能得到正确结果)
  • 区别:summarise_at是对列做汇总,返回单行结果;而mutate配合rowMeans/across是对行做计算,给每行新增对应的值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 14:36:19