按行和列平均
Average by row and column
我有一个大矩阵,对于每个单元格,我想计算落在该特定单元格的列和行中的数字的平均值。
由于矩阵包含 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)
我有一个大矩阵,对于每个单元格,我想计算落在该特定单元格的列和行中的数字的平均值。
由于矩阵包含 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)