Search code examples
rmatrixcoercion

Why does as.numeric convert a matrix to a vector, and how do I keep the result as a matrix?


The following code converts a 3x3 logical matrix into a vector with 9 elements:

as.numeric(matrix(rep(FALSE, 9), nrow = 3))
# [1] 0 0 0 0 0 0 0 0 0

Why is this happening and how do I avoid this? Apologies if this has been asked before, the only reference I could find was: https://stackoverflow.com/a/15490316/


Solution

  • One option is to create an object earlier and then assign the output back to it

    m1 <- matrix(rep(FALSE, 9), nrow = 3)
    m1[] <- as.numeric(m1)
    

    or a hacky option is

    +(matrix(rep(FALSE, 9), nrow = 3))
    #     [,1] [,2] [,3]
    #[1,]    0    0    0
    #[2,]    0    0    0
    #[3,]    0    0    0
    

    Or assign with the dim

    `dim<-`(as.numeric(matrix(rep(FALSE, 9), nrow = 3)), c(3, 3))