Sunday, September 13, 2015

Useful R tips #2

Bit manipulation


Using &, |, and !, >>, <<,  ^ on values and expressions in R do not produce the expected binary operation result. These are all used for logical expressions (except for ^, which is used to raise a value or an expression to an exponent) and not bit-wise operations. Instead, the following functions are available:

NEG (negation, transform bit 0 to 1, and vice versa)

bitwNot(a) 

AND ( a & b )

bitwAnd(a, b) 

OR ( a | b )
bitwOr(a, b)

XOR ( a ^ b )

bitwXor(a, b)

SHL, Shift-Left ( a << b )

bitwShiftL(a, n)

SHR, Shift-Right ( a >> b )

bitwShiftR(a, n)

IN, NOT IN operations on vectors and arrays

A quick and easy way to check if elements of one array are present in another array is the use of the %in% operator. For example

a = c(1,2,3,4,5)
b = c(2,4,6)

Elements of a that are present in b

> a[a %in% b]
[1] 2 4

Elements of a that are not present in b

> a[!(a %in% b)]
[1] 1 3 5

Similary, for b, the elements are present in a

> b[b %in% a]
[1] 2 4

Elements of b that are not present in a

> b[!(b %in% a)]
[1] 6


No comments:

Post a Comment