Matrix Multiplication with Scattered NA Values

I want to multiply two matrices together in R, one of which may contain randomly placed NA values ​​(i.e. there is no reason why they will all be in a row or column), but I still need an output similar to the example below:

Matrix 1 [1,] 33 45 50 [2,] NA NA 54 Matrix 2 [1,] A1 0.0000000 0.0000000 [2,] 0.0000000 A2 0.0000000 [3,] 0.0000000 0.0000000 A3 Result [1,] 33*A1 45*A2 50*A3 [2,] NA NA (NA*0 +NA*0 +54*A3)=54*A3 

Just executing Matrix1% *% Matrix2 does not give what I want for the element in row 2, column 3 (it gives NA, which makes sense, but is not sure how to do what I would like to do), For my purposes, Matrix 2 will never have NA values ​​if that changes anything.

+4
source share
1 answer

Change all occurrences of NA to 0, then do matrix multiplication:

 x <- matrix(c(33, 45, 50, NA, NA, 54), nrow=2, byrow=TRUE) y <- diag(1:3) x[is.na(x)] <- 0 x %*% y [,1] [,2] [,3] [1,] 33 90 150 [2,] 0 0 162 
+7
source

Source: https://habr.com/ru/post/1480626/


All Articles