行和列的平均值

问题描述 投票:0回答:1

我有一个大矩阵,我想为每个单元格计算该特定单元格的列和行中的平均数字。

由于矩阵包含NA值,我对跳过它们不感兴趣

我该如何加快并做得更好?

谢谢

mtx <- matrix(seq(1:25), ncol = 5)
mtx[2,3] <- NA

mean.pos <- mtx
for(i in 1:dim(mtx)[1]){

  for(j in 1:dim(mtx)[2]){

    if(is.na(mtx[i,j])){

    } else {
      row.values <- mtx[i, !is.na(mtx[i,])]

      # -- Remove mtx[i,j] value itself to not count it twice
      row.values <- row.values[-which(row.values == mtx[i,j])[1]]

      col.values <- mtx[!is.na(mtx[,j]),j]
      mean.pos[i,j] <- mean(c(row.values, col.values), na.rm = T)
    }      
  }
}
r row calculator
1个回答
1
投票

此操作无需显式遍历元素。

num <- outer(rowSums(mtx, na.rm = TRUE), colSums(mtx, na.rm = TRUE), "+") - mtx
not_na <- !is.na(mtx)
den <- outer(rowSums(not_na), colSums(not_na), "+") - 1
result <- num/den

# check
identical(result, mean.pos)
## [1] TRUE

如果没有NA,则可以简化为:

(outer(rowSums(mtx), colSums(mtx), "+") - mtx) / (sum(dim(mtx)) - 1)
© www.soinside.com 2019 - 2024. All rights reserved.