惯用的矩阵类型转换,例如将整数(0/1)矩阵转换为布尔矩阵 [英] Idiomatic matrix type conversion, say convert Integer (0/1) matrix to boolean matrix

查看:512
本文介绍了惯用的矩阵类型转换,例如将整数(0/1)矩阵转换为布尔矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

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

我想要:

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

as.logical(B)提供一维矢量.是否有惯用的方式进行矩阵类型转换?

as.logical(B)gives a 1D vector. Is there an idiomatic way to do the matrix type conversion?

我目前正在罗word:

I'm currently doing the wordy:

boolVector <- as.logical(B)

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

m <- matrix(boolVector, m , n)
m

推荐答案

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

mode(B) <- "logical" or "mode<-"(B, "logical"). We can also use storage.mode function.

此解决方法很好,有两个原因:

This workaround is good for two reasons:

  1. 代码易读;
  2. 该逻辑通常有效(请参见下面的示例).

当我读取带有编译代码的某些软件包的源代码时,我学到了这个技巧.当将R数据结构传递给C或FORTRAN函数时,可能需要某种类型的强制,并且它们通常为此目的使用modestorage.mode.这两个函数都保留R对象的属性,例如矩阵的暗"和暗名".

I learnt this trick when reading source code of some packages with compiled code. When passing R data structures to C or FORTRAN functions, some type coercion may be required and they often use mode or storage.mode for this purpose. Both functions preserve attributes of R objects, like "dim" and "dimnames" of matrices.

## 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中有许多模式,但是矢量只允许其中一些模式.我在我的答案中对此进行了介绍.

Note that mode changing is only possible between legitimate modes of vectors (see ?vector). There are many modes in R, but only some are allowed for a vector. I covered this in my this answer.

此外,"factor"不是向量(请参见?vector),因此您无法对factor变量进行模式更改.

In addition, "factor" is not a vector (see ?vector), so you can't do mode change on a factor variable.

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

这篇关于惯用的矩阵类型转换,例如将整数(0/1)矩阵转换为布尔矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆