0

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)?

micstr
  • 5,080
  • 8
  • 48
  • 76
  • 1
    Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – zx8754 Jul 28 '16 at 10:24

2 Answers2

3

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.

data

X1 <- matrix(1:9, 3, 3)
X2 <- matrix(c(NA, "a", "b", "c",  "a", NA, "c","f", "a"), 3, 3)
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662
2

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213