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

在R中计算多个带索引列表相同索引位置的均值

在R语言中按索引计算多个列表的元素平均值

我有4个以带索引列表形式呈现的预测y值:

> y_a
       2       12       15       19       20       22        3        4 
26.05434 24.33894 38.57935 37.94003 23.87608 46.20327 18.43043 24.96521 
       5        8       13       21        1        7       10       11 
17.34129 30.41087 28.49836 39.02917 21.96358 30.41087 23.61032 30.41087 
      16       18 
35.31196 35.85652 
> y_b
       6        9       14       17       23       24        3        4 
36.87726 35.30301 40.48044 38.24398 42.67726 41.31053 32.32106 33.81204 
       5        8       13       21        1        7       10       11 
32.07257 35.05451 40.31655 44.74850 38.82558 35.05451 27.80451 35.05451 
      16       18 
36.17274 36.29699 
> y_c
       6        9       14       17       23       24        2       12 
30.24043 35.33617 39.18723 33.63404 42.76170 39.36809 32.25106 24.04894 
      15       19       20       22        1        7       10       11 
39.34681 38.28298 31.01702 43.66596 33.19787 34.71915 27.60213 34.71915 
      16       18 
37.49574 37.80426 
> y_d
       6        9       14       17       23       24        2       12 
26.48159 35.12368 38.41591 31.00840 40.54660 36.01979 31.00840 22.70478 
      15       19       20       22        3        4        5        8 
40.47355 32.72757 29.36229 46.23494 25.24701 30.18534 24.42395 34.30063 
      13       21 
32.72757 33.55063 

需要生成新列表y_mean,其中每个元素为所有列表相同索引位置元素的平均值,比如索引2、12、15等位置的均值,具体实现方法如下:

方法一:基础R实现

无需额外安装包,直接通过索引遍历计算:

# 收集所有唯一索引
all_indices <- unique(c(names(y_a), names(y_b), names(y_c), names(y_d)))

# 对每个索引计算对应元素的平均值
y_mean <- sapply(all_indices, function(idx) {
  # 收集当前索引在四个列表中的所有值
  vals <- c(
    if (idx %in% names(y_a)) y_a[idx],
    if (idx %in% names(y_b)) y_b[idx],
    if (idx %in% names(y_c)) y_c[idx],
    if (idx %in% names(y_d)) y_d[idx]
  )
  # 计算均值
  mean(vals)
})

# 查看结果
y_mean

方法二:dplyr包实现(tidyverse风格)

适合习惯tidyverse语法的用户,步骤更直观:

# 若未安装dplyr先运行:install.packages("dplyr")
library(dplyr)

# 将每个列表转换为包含索引和值的数据框
df_a <- data.frame(index = names(y_a), value = as.numeric(y_a))
df_b <- data.frame(index = names(y_b), value = as.numeric(y_b))
df_c <- data.frame(index = names(y_c), value = as.numeric(y_c))
df_d <- data.frame(index = names(y_d), value = as.numeric(y_d))

# 合并数据框,按索引分组计算均值
y_mean_df <- bind_rows(df_a, df_b, df_c, df_d) %>%
  group_by(index) %>%
  summarise(mean_value = mean(value))

# 转换为带索引的列表形式
y_mean <- setNames(y_mean_df$mean_value, y_mean_df$index)

# 查看结果
y_mean

两种方法最终都会得到带索引的列表y_mean,每个索引对应的元素是四个原始列表中该索引位置所有值的平均值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:15:28