Idiomatic matrix type conversion, say convert Integer (0/1) matrix to boolean matrix

后端 未结 2 1277
渐次进展
渐次进展 2021-01-21 06:39

I have:

 B <- matrix(c(1, 0, 0, 1, 1, 1), 
             nrow=3, 
             ncol=2)

and I want:

 B
      [,1] [,2]
[1,]           


        
2条回答
  •  面向向阳花
    2021-01-21 07:10

    A matrix is a vector with dim attributes. When we apply as.logical, the dim attributes are lost. It can be assigned with dim<-

    `dim<-`(as.logical(B), dim(B))
    #      [,1] [,2]
    #[1,]  TRUE TRUE
    #[2,] FALSE TRUE
    #[3,] FALSE TRUE
    

    Or another option is create a logical condition that preserves the attribute structure

    B != 0
    

    Or

    !!B
    

提交回复
热议问题