書籍が見つからない
Rの書籍は色々持っているものの、bit演算や複素数型について詳しく説明されているものってないような気がします。
なので、ちょっと調べました。
先人のお知恵を拝借。 takuyaokada.hatenablog.com
R.utilsというパッケージもあるのですね。これも後ほど調べてみる。
RStudioの入力補完でそれらしいものを見つける
RStudioでbitまで入力して補完を使うと、bitopsというパッケージがある。
baseと別にあるということは、より良いのでは?ということで違いを見てみる。
いくつか入力してみる。
> bitwAnd(15,0) [1] 0 > bitwAnd(15,7) [1] 7 > bitops::bitAnd(15,7) [1] 7 > 15 & 7 [1] TRUE
最後はおまけ。&はlogicalを返しますので、bit演算には使えませぬ。
差異はないように見えますね。
ベクトルでも入力できる。
> bitwAnd(c(15,0),7) [1] 7 0 > bitops::bitAnd(c(15,0),7) [1] 7 0 > bitops::bitAnd(c(15,0,1),c(7,1,3)) [1] 7 0 1 > bitwAnd(c(15,0,1),c(7,1,3)) [1] 7 0 1
ここでも差異がみえない。ベクトルを与えられるのは便利ですね。
ヘルプを見るとNAについて記述がある。入力してみる。
> bitops::bitAnd(c(15,0),NA) [1] NA NA > bitwAnd(c(15,0),NA) Error in bitwAnd(c(15, 0), NA) : 'a' and 'b' must have the same type
おっと、差異が出ました。baseの方はNAを入れるとエラー…
( ^ω^)・・・
type…?どうやら、NAがintegerだと思われていないようです。
今度は、NA_integer_で入れてみる。
> bitwAnd(c(15,0),NA_integer_) [1] NA NA
お、動きますね。
念のため、もう一方も。
> bitops::bitAnd(c(15,0),NA_integer_) [1] NA NA
こちらも。
bitopsパッケージの方を使っておいた方が、NAの型を合わせてくれるので便利そうです。
ヘルプより、
bitwise {base} bitwAnd(a, b) a, b integer vectors; numeric vectors are coerced to integer vectors
もう一方
bitAnd {bitops} bitAnd(a, b) a,b numeric vectors of compatible length.
integer… 試しに入力すると…
> bitops::bitAnd(c(15.12501,0,1),c(7,1,3)) [1] 7 0 1 > bitwAnd(c(15.01,0,1),c(0.999,1,3)) [1] 0 0 1 > bitwAnd(c(15.01,0,1),c(1.999,1,3)) [1] 1 0 1
なるほど。使い方を気を付けないといけなさそうです。