Использование функции matrix()
и ncol()
и nrow()
# Using the data Ronak Shah provided
mat <- matrix(1:15, ncol = 3)
# Solution
mat2 <-
# matrix mean
mean(mat) +
# column means
matrix(rep(colMeans(mat), nrow(mat)), nrow = nrow(mat), byrow = TRUE) +
# row means
matrix(rep(rowMeans(mat), ncol(mat)), nrow = nrow(mat), byrow = FALSE)
Возвращает
> mat
[,1] [,2] [,3]
[1,] 1 6 11
[2,] 2 7 12
[3,] 3 8 13
[4,] 4 9 14
[5,] 5 10 15
> mat2
[,1] [,2] [,3]
[1,] 17 22 27
[2,] 18 23 28
[3,] 19 24 29
[4,] 20 25 30
[5,] 21 26 31
mat2[1,1]
, например = mean(mat) + colMeans(mat)[1] + rowMeans(mat)[1]
= 8 + 3 + 6 = 17
Если вы хотите использовать его для замены NA в исходной матрице, просто добавьте na.rm = TRUE
ко всем вашим средним функциям, затем сравним матрицы с is.na()
и переопределим
mat <- matrix(1:15, ncol = 3)
mat[1,2] <- mat[4,3] <- NA
# Solution
mat2 <-
# matrix mean
mean(mat, na.rm = TRUE) +
# column means
matrix(rep(colMeans(mat, na.rm = TRUE), nrow(mat)), nrow = nrow(mat), byrow = TRUE) +
# row means
matrix(rep(rowMeans(mat, na.rm = TRUE), ncol(mat)), nrow = nrow(mat), byrow = FALSE)
# Replace the NAs
mat[is.na(mat)] <- mat2[is.na(mat)]
Даёт
[,1] [,2] [,3]
[1,] 1 22.19231 11.00000
[2,] 2 7.00000 12.00000
[3,] 3 8.00000 13.00000
[4,] 4 9.00000 26.94231
[5,] 5 10.00000 15.00000