I have two matrices, X1 and X2, with the same dimensions.
X2 has NAs values.
How can I put NAs values in X1 in the same position of X2 (replacing the values in X1)?
I have two matrices, X1 and X2, with the same dimensions.
X2 has NAs values.
How can I put NAs values in X1 in the same position of X2 (replacing the values in X1)?
We can use replace
replace(X1, is.na(X2), NA)
# [,1] [,2] [,3]
#[1,] NA 4 7
#[2,] 2 5 8
#[3,] 3 NA 9
Or
X1 * NA^is.na(X2)
# [,1] [,2] [,3]
#[1,] NA 4 7
#[2,] 2 5 8
#[3,] 3 NA 9
Or as @Roland mentioned in the comments
is.na(X1) <- is.na(X2)
BTW,
X1 + X2 - X2
#Error in X1 + X2 : non-numeric argument to binary operator
Bottomline is that both the solutions I posted is general and works for non-numeric matrices as well.
X1 <- matrix(1:9, 3, 3)
X2 <- matrix(c(NA, "a", "b", "c", "a", NA, "c","f", "a"), 3, 3)
You can do
X1[is.na(X2)] <- NA
In case if the data is completely numeric,try
NA
+ any number is NA
. You can add X2
and then subtract it.
X1 + X2 - X2