Matrix multiplication with scattered NA values
Asked Answered
G

2

8

I'm looking to multiply two matrices together in R, one of which may contain randomly placed NA values (i.e., there's no reason they will be all in a row or column), but I still want an output like 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

Simply doing Matrix1%*%Matrix2 doesn't give what I want for the element in Row 2, Column 3 (it gives NA, which makes sense, but not sure how to do what I'd like it to do). For my purposes, Matrix 2 will never have NA values, if that changes anything.

Gentlewoman answered 14/5, 2013 at 4:23 Comment(1)
I was expecting to find an inner function to match R's outer function, allowing you to write your own custom operation like this. Oh well, it looks like it does not exist. I wonder why.Ostensorium
A
13

Change all occurrences of NA to 0, then do the 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
Alper answered 14/5, 2013 at 4:45 Comment(1)
The only trick would be converting those 2 0's in the result to NA's. In my case, the distinction is that exp(0)=1, whereas exp(NA)=NA. When operating on a log scale, I use NA to represent "nothing".Microcline
M
4

To expand on the previous answer and its comment: you can apply the NA pattern of the input matrix into the output matrix.

This works only if input and output matrices are of the same dimension.

x <- matrix(c(33, 45, 50, NA, NA, 54), nrow=2, byrow=TRUE)
y <- diag(1:3)

x0 <- x
x0[is.na(x)] <- 0

z <- x0 %*% y

z[is.na(x)] <- NA

z
     [,1] [,2] [,3]
[1,]   33   90  150
[2,]   NA   NA  162
Melodramatize answered 18/7, 2018 at 11:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.