I have a large matrix, for each cell I want to calculate the average of the numbers falling in the column and row of that specific cell.
As the matrix contains NA values and I'm not interested in those I skip them
How could I speed-up this and do it better?
Thanks
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)
}
}
}