r - How to replace numbers with NAs with condition -


i have 2 matrices, x1 , x2, same dimensions.

x2 has nas values.

how can put nas values in x1 in same position of x2 (replacing 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 @roland mentioned in comments

is.na(x1) <- is.na(x2) 

btw,

x1 + x2 - x2 #error in x1 + x2 : non-numeric argument binary operator 

bottomline both solutions posted general , works non-numeric matrices well.

data

x1 <- matrix(1:9, 3, 3) x2 <- matrix(c(na, "a", "b", "c",  "a", na, "c","f", "a"), 3, 3) 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -