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
Post a Comment