Overview of Extended Binary Operators for Data Manipulation
James J Balamuta
2025-05-27
Source:vignettes/rops.Rmd
rops.Rmd
Overview
When writing functions or simply perform data analyses, sometimes you may wish for just that one additional operator or equality check that speeds up the process greatly. The goal behind this package is to provide such operators with as minimal an overhead as possible.
Coalescing Operators
Null coalescing operator
# Null value
x = NULL
# Before
y = if(is.null(x)){ "Unset" } else { x }
# After
y = x %??% "Unset"
y
## [1] "Unset"
Equality Operators
Checking for exact equivalence in object can be done using an infix
operator instead of relying upon identical()
.
NB There are cases where checking with
all.equal()
is preferred.
x = y = 1:5
x2 = x + 1
# Before
identical(x, y)
## [1] TRUE
identical(x2, y)
## [1] FALSE
# After
x %==% y
## [1] TRUE
x2 %==% y
## [1] FALSE
# Before
!identical(x, y)
## [1] FALSE
!identical(x2, y)
## [1] TRUE
# After
x %!=% y
## [1] FALSE
x2 %!=% y
## [1] TRUE
Whole Numbers
Previously, using is.integer()
would yield a check on
the type of vector. Here, the is_whole()
function seeks to
check the state of all numbers individually in the vector regardless of
whether they are numeric
or integer
.
x = c(1, 2, 3, 8.5)
y = c(1L, 2L, 3L)
# Before
is.integer(x)
## [1] FALSE
is.integer(y)
## [1] TRUE
# After
is_whole(x)
## [1] TRUE TRUE TRUE FALSE
is_whole(y)
## [1] TRUE TRUE TRUE
Safe Sequence Generation
The colon operator (:
) does not perform a check on
whether the increment should be positive or negative. This leads to
issues when iterating over an empty vector
or
data.frame
using 1:length(obj)
. To avoid this,
safe sequences %:%
performs a check to make sure the
sequence is positive. If it is not, then an empty integer
vector is created to avoid having a loop run.
x = NULL
# Before
1:length(x)
## [1] 1 0
## integer(0)