惯用的矩阵类型转换,将整数(0/1)矩阵转换为布尔矩阵。

4

我有:

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

and I want:

 B
      [,1] [,2]
[1,]  TRUE TRUE
[2,] FALSE TRUE
[3,] FALSE TRUE

as.logical(B)会给出一个一维向量。是否有一种惯用的方式来进行矩阵类型转换?

我目前在使用冗长的方法:

boolVector <- as.logical(B)

m <- nrow(B)
n <- ncol(B)

m <- matrix(boolVector, m , n)
m
2个回答

8

mode(B) <- "logical""mode<-"(B, "logical")。我们还可以使用storage.mode函数。

这个解决方法有两个好处:

  1. 代码更易读;
  2. 逻辑在一般情况下都可行(见下面的示例)。

我在阅读一些带有编译代码包的源代码时学到了这个技巧。当将 R 数据结构传递给 C 或 FORTRAN 函数时,可能需要进行某些类型强制转换,它们通常使用 modestorage.mode 来实现。这两个函数都保留 R 对象的属性,如矩阵的 "dim" 和 "dimnames"。

## an integer matrix
A <- matrix(1:4, nrow = 2, dimnames = list(letters[1:2], LETTERS[1:2]))
#  A B
#a 1 3
#b 2 4

"mode<-"(A, "numeric")
#  A B
#a 1 3
#b 2 4

"mode<-"(A, "logical")
#     A    B
#a TRUE TRUE
#b TRUE TRUE

"mode<-"(A, "chracter")
#  A   B  
#a "1" "3"
#b "2" "4"

"mode<-"(A, "complex")
#     A    B
#a 1+0i 3+0i
#b 2+0i 4+0i

str("mode<-"(A, "list"))  ## matrix list
#List of 4
# $ : int 1
# $ : int 2
# $ : int 3
# $ : int 4
# - attr(*, "dim")= int [1:2] 2 2
# - attr(*, "dimnames")=List of 2
#  ..$ : chr [1:2] "a" "b"
#  ..$ : chr [1:2] "A" "B"

请注意,模式更改仅适用于向量的合法模式(请参见?vector)。在R中有许多模式,但只有一些模式适用于向量。我在我的这个答案中涵盖了这一点。
另外,“因子”不是向量(请参见?vector),因此您无法对因子变量进行模式更改。
f <- factor(c("a", "b"))

## this "surprisingly" doesn't work
mode(f) <- "character"
#Error in `mode<-`(`*tmp*`, value = "character") : 
#  invalid to change the storage mode of a factor

## this also doesn't work
mode(f) <- "numeric"
#Error in `mode<-`(`*tmp*`, value = "numeric") : 
#  invalid to change the storage mode of a factor

## this does not give any error but also does not change anything
## because a factor variable is internally coded as integer with "factor" class
mode(f) <- "integer"
f
#[1] a b
#Levels: a b

4

矩阵是一个带有维度属性的向量。当我们使用as.logical时,维度属性会丢失。可以使用dim<-进行赋值。

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

另一个选项是创建一个保留属性结构的逻辑条件。
B != 0

或者
!!B

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接