如何汇总数值列表元素

时间:2012-01-20 10:16:36

标签: r

我想知道一种优雅的方式,允许对列表的数值求和(或计算平均值)。 e.g。

x <- list( a = matrix(c(1,2,3,4), nc=2), b = matrix(1, nc=2, nr=2))

想要

x[[1]]+x[[2]] 

或者意思是:

(x[[1]]+x[[2]])/2

2 个答案:

答案 0 :(得分:70)

您可以使用Reduce将二进制函数连续应用于列表中的元素。

Reduce("+",x)
     [,1] [,2]
[1,]    2    4
[2,]    3    5

Reduce("+",x)/length(x)
     [,1] [,2]
[1,]  1.0  2.0
[2,]  1.5  2.5

答案 1 :(得分:1)

即使Reduce()是矩阵列表求和问题的标准答案,并且已经多次指出,我还是在以下代码中收集了一些最重要的方法来实现此目标。主要目的是显示在速度和“精度”方面是否有明显比其他选择更好的选择。

# load libraries
library(microbenchmark)
library(ggplot2)

# generate the data with ten matrices to sum
mat_list <- lapply(1:10, function(x) matrix(rnorm(100), nrow = 10, ncol = 10))
# larger and longer test set
mat_list_large <- lapply(1:1000, function(x) matrix(rnorm(100000), nrow = 1000, ncol = 100))

# function with reduce @james
f1 <- function(mat_list){
  Reduce(`+`, mat_list)
}
# function with apply @Jilber Urbina
f2 <- function(mat_list){
  apply(simplify2array(mat_list), c(1:2), sum)
}
# function with do.call @Tyler Rinker
f3 <- function(mat_list){
  x <- mat_list[[1]]
  lapply(seq_along(mat_list)[-1], function(i){
    x <<- do.call("+", list(x, mat_list[[i]]))
  })
  return(x)
}
# function with loop modified from @Carl Witthoft
f4 <- function(mat_list){
  out_mat <- mat_list[[1]]
  for (i in 2:length(mat_list)) out_mat <- out_mat + mat_list[[i]]
  return(out_mat)
}

# test to see if they are all equal
all.equal(f1(mat_list), f2(mat_list), f3(mat_list), f4(mat_list), tolerance = 1.5e-8) # TRUE 
# ps: the second method seems to differ slightly from the others

# run 100 times all the functions for having a statistic on their speed
mb <- microbenchmark("Reduce" = f1(mat_list),
                     "apply" = f2(mat_list),
                     "do.call" = f3(mat_list),
                     "loop" = f4(mat_list), 
                     times = 100)
mb2 <- microbenchmark("Reduce" = f1(mat_list_large),
                 "apply" = f2(mat_list_large),
                 "do.call" = f3(mat_list_large),
                 "loop" = f4(mat_list_large), 
                 times = 100)

# see output using a violin plot
autoplot(mb)

mat_list_sum_speed

autoplot(mb2) # longer version for bigger datasets

mat_list_sum_speed_large

因此,最好使用Reduce()来提高中间速度和代码的清晰度。