Home > Software engineering >  Copy matrix, but substituting non NA values to TRUE, and NAs to FALSE
Copy matrix, but substituting non NA values to TRUE, and NAs to FALSE

Time:03-20

How do I get from

test <- matrix(c("eb2","ebrees",NA,NA,
                 "ebrees","es2",NA,NA,
                  NA, NA, NA, NA,
                  NA, NA, NA, NA), ncol = 4, byrow = T)

     [,1]     [,2]     [,3] [,4]
[1,] "eb2"    "ebrees" NA   NA
[2,] "ebrees" "es2"    NA   NA
[3,] NA       NA       NA   NA
[4,] NA       NA       NA   NA

to:

     [,1] [,2] [,3] [,4]
[1,]   T    T    F   F
[2,]   T    T    F   F
[3,]   F    F    F   F
[4,]   F    F    F   F

Here is how far I got:

which( !is.na(test), arr.ind = TRUE)

     row col
[1,]   1   1
[2,]   2   1
[3,]   1   2
[4,]   2   2

which gives me the numerical version of what I need.

A second attempt was to treat the matrix as df, but returned me char instead of logic, , seems like I am close but can't figure out how to get the logic values.

test[!is.na(test)] = T
test[is.na(test)] = F

CodePudding user response:

test1 <- (!is.na(test))

Output

> test1
      [,1]  [,2]  [,3]  [,4]
[1,]  TRUE  TRUE FALSE FALSE
[2,]  TRUE  TRUE FALSE FALSE
[3,] FALSE FALSE FALSE FALSE
[4,] FALSE FALSE FALSE FALSE
  • Related