初始化boolean矩阵_惯用的矩阵类型转换,例如将整数(0/1)矩阵转换为布尔矩阵...

在R语言中,当有一个整数矩阵(如B),需要将其转换为布尔矩阵时,通常的做法可能会得到一维向量。通过使用`mode()`或`storage.mode()`函数可以实现矩阵类型的转换,同时保持矩阵的属性如“dim”和“dimnames”。本文介绍了一种简洁的转换方法,并解释了为何这种方法在涉及与C或FORTRAN函数交互时尤其有用。同时,文中也指出模式转换仅限于合法的向量模式,并且不能对因子变量进行模式改变。
摘要由CSDN通过智能技术生成

I have:

B

nrow=3,

ncol=2)

and I want:

B

[,1] [,2]

[1,] TRUE TRUE

[2,] FALSE TRUE

[3,] FALSE TRUE

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

I'm currently doing the wordy:

boolVector

m

n

m

m

解决方案

mode(B)

This workaround is good for two reasons:

the code is much readable;

the logic works in general (see examples below).

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 matrice

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值