r - 按行和列平均
问题描述
我有一个大矩阵,对于每个单元格,我想计算落在该特定单元格的列和行中的数字的平均值。
由于矩阵包含 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)
}
}
}
解决方案
这样做无需显式循环遍历元素。
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)
推荐阅读
- python - 未找到文件,但文件已下载
- python - 与 pandas 聚合
- python - 在 pandas 中加载一个非常大的 jsonl 会返回 ValueError
- python - 定义 FK 和子关系时的交叉引用 SQLAlchemy
- data-visualization - 如何根据 Tableau 中的度量值创建集合?
- dolphindb - 如何删除 DolphinDB 中的所有用户名?
- c - 分配给 sigaction 结构的 sa_mask 字段的正确值是什么
- java - 在片段中单击按钮时没有任何反应
- python - 缺少 1 个必需的位置参数?
- r - FE 回归中的 Driscoll 和 Kraay 标准误差:在 R 中再现 Stata xtscc 输出