Return 数据帧列表中的平均值数据帧

Return a dataframe of averages from a list of dataframes

我有一个包含 22 个数据帧的列表,每个数据帧有 49 列和 497 行。

我需要从这 22 个中生成一个 average/mean 数据框。

已经试过了,myfiles2是dataframes列表

    ans1 = aaply(laply(myfiles2, as.matrix), c(2, 3), mean)

    ans2 <- do.call("mean", myfiles2)

    ans3 <- lapply(myfiles2, function (x) lapply(x, mean, na.rm=TRUE))

    ans4 <- Reduce("+", myfiles2)/length(myflies2)

    ans5 <- lapply(myfiles2, mean)

数据帧列表是使用

创建的
    myfiles2 = lapply(filesToProcess, read.csv, skip=2, colClasses=colClasses)

手动获取每个数据框中的第一个值并使用 mean() 计算平均值。

如上所示在数据帧列表中尝试使用均值或计算均值会给出错误的结果。

我正在寻找的结果是一个 [49X497] 数据帧,每个位置都包含从 22 个数据帧中的相同位置计算的平均值。

所有值都是 10 位有效数字,小数点后 4 位。

使用 abind 包从 data.frames;

列表创建 3D 数组
library(abind)
myfiles2 <- abind(myfiles2, along = 3)

或在 Base R 中:

myfiles2 <- simplify2array(myfiles2)

然后,使用 apply() 取所有 22 个单元格的平均值 data.frames:

apply(myfiles2, 1:2, mean)

您可以在基础 R 中使用 simplify2array()

示例

list1
# [[1]]
#      [,1] [,2] [,3] [,4]
# [1,]    1    9    8    3
# [2,]    5    2    6   11
# [3,]   12    4   10    7
# 
# [[2]]
#      [,1] [,2] [,3] [,4]
# [1,]    4   12    3    6
# [2,]    9    2    1    7
# [3,]    5    8   10   11
# 
# [[3]]
#      [,1] [,2] [,3] [,4]
# [1,]    5    8    1   12
# [2,]    4    3    7    6
# [3,]    2   10   11    9

t(apply(simplify2array(list1), 1:2, mean))
#          [,1]     [,2]      [,3]
# [1,] 3.333333 6.000000  6.333333
# [2,] 9.666667 2.333333  7.333333
# [3,] 4.000000 4.666667 10.333333
# [4,] 7.000000 8.000000  9.000000

数据

set.seed(42)
list1 <- replicate(3, matrix(sample(1:12), 3, 4), simplify=FALSE)

根据上述@tom 的提示,最终解决方案是将数据帧列表更改为包含所有数据的单个数据帧,并使用 tidyverse 对其进行处理。

需要一些小的整理。

  1. 来自数据来源的错误字符列
  2. 包含大写和小写数据的列
  3. 避免均值计算中的字符列
  4. 然后将字符列和均值数据框放回原处,使其按正确的顺序恢复。

所以...

将格式更改为单个数据框并修复非数字列

myfiles3 <- myfiles2 %>% 
  bind_rows() %>%
  transform(EdgeStepL2 = as.numeric(EdgeStepL2))

确保部分名称大写以保持一致

myfiles3$Section <- str_to_upper(myfiles3$Section)

计算按公共值分组的每个单元格的平均值。

myfiles4 <- myfiles3 %>% group_by(Section,Chainage) %>%
  summarise_at(vars("East":"Surf.Det"),funs(mean(., na.rm = TRUE)))

myfiles5 <- data.frame(myfiles2[[1]][1:2])

myfiles6 <- left_join(myfiles5, myfiles4)

这不是我所希望的简单解决方案,而是供下一个人尝试的解决方案。

查找 NA(数据中的所有位置)。

确保您作为运行平均值(或其他函数)的所有列都是您可以用来计算的列。