计算R中多个矩阵的均值

时间:2014-09-24 09:04:55

标签: r

什么是计算相同维度的多个矩阵的平均值的有效方法?

如果A,B是2 x 2矩阵那么,

A
2  3
4  5

B
6  7
8  9

意味着(A,B)应该给出

4  5
6  7

简单的方法是做(A + B + ...)/数量的矩阵。 (并明确处理NA值)

任何其他优雅的方法或库(支持na.rm)?

3 个答案:

答案 0 :(得分:9)

将它们组合成一个数组并使用apply

A <- matrix(c(2,4,3,5), 2)
B <- matrix(c(6,8,7,9), 2)

X <- list(A, B)
Y <- do.call(cbind, X)
Y <- array(Y, dim=c(dim(X[[1]]), length(X)))

apply(Y, c(1, 2), mean, na.rm = TRUE)
#     [,1] [,2]
#[1,]    4    5
#[2,]    6    7

如果apply效率不高,您可以将colMeans(提供NA处理)与aperm一起使用:

colMeans(aperm(Y, c(3, 1, 2)), na.rm = TRUE)
#     [,1] [,2]
#[1,]    4    5
#[2,]    6    7

答案 1 :(得分:1)

我认为purrr::reduce对此有更好的解决方案。

require(purrr)
x = list(volcano+10, volcano-15, volcano-5)
v = reduce(x, `+`) / length(x)
image(v)

enter image description here

答案 2 :(得分:0)

如果您希望结果是具有相同列名和行名的矩阵,您可以创建一个函数来将您的矩阵列表传递给。您还可以将应用函数从 mean 更改为 sd 或任何其他。

let obj = {};

// methods with fetch ideally should be specified async.
// async calls will automatically return a promise
obj.start = async () => {
  console.log('start begins')
  let retText = "",
    fetcher = fetch('/', {}).then(response => response.text())
    .then(text => {
      console.log('fetch\'s last then')
      retText = text
    })
  // fetcher has just been declared. It hasn't done anything yet.
  console.log('fetch requested, returned length:', retText.length)

  // this makes the fetcher and sequential then's happen
  await fetcher;
  console.log('await let fetch finish, returned length:', retText.length)

  // Async functions will return a promise, but the return specified here
  // will be passed to the next 'then'
  return obj
}
obj.middle = () => {
  console.log('middle called')
  // Because this is not declared async, it behaves normally
  return obj;
}
obj.end = () => {
  console.log('end called')
  // Because this is not declared async, it behaves normally
}

console.log('Method 1: ', obj.start()
  // Because start is Async, it returns obj wrapped in a promise.
  // As with any function, step may be named Anything you like
  .then((step) => step.middle())
  // Middle is not Async, but since it's wrapped in then
  // it returns a promise
  .then((step) => step.end())
)

// This is just wrapped in a timer so the two logs don't intermix with each other

// This is definitely the preferred method. Non-async chain-methods that return 
// a reference to their object, do not need to wrapped in then().
setTimeout(function() {
  console.log('------------------------')
  console.log('Method 2: ', obj.start()
    // Because start is Async, it returns obj wrapped in a promise.
    // As with any function, step may be named Anything you like
    .then((step) => step.middle().end())
  )
}, 3000)