Nullable Optional Arguments in Rcpp functions
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Introduction
Often we need to have optional arguments in R
of Rcpp
functions with default values. Sometimes,
the default value for the optional parameters is set to be NULL
. Rcpp
provides the Nullable <>
to set default value as to be R_NilValue
(equivalent of NULL
in Rcpp
). There have been several
StackOverflow posts on using the
Nullable
behavior. As seen from quite a few posts, the key step in using Rcpp::Nullable<>
is
to cast it to the underlying type first (i.e., instantiation) after checking that the input is not
NULL
.
Nullability of Vector, Matrix or Logical Vector
Running a few examples with setting NULL
for a vector, matrix or a boolean value gives us the
expected results.
Numeric Vector is set to not NULL. 1 2
Numeric Matrix is set to not NULL. -0.500000 -0.500000 -0.500000 -0.500000 -0.500000 -0.500000 -0.500000 -0.500000 -0.500000
Logical Vector is set to not NULL. 0
Warning in nullable1(NULL, NULL, NULL): All arguments are set to NULL.
Warning in nullable1(c(), NULL, NULL): All arguments are set to NULL.
We get the same result when the input to the NumericVector
argument is not NULL
but an empty
vector, i.e., c()
, which is also expected since is.null(c())
is TRUE
in R
.
A stricter test whether the input is usable can be (aptly named) isUsable()
.
Nullability of DataFrame and List
Rcpp::Nullable<>
works for SEXP
based Rcpp
types, so Rcpp::DataFrame
and Rcpp::List
can
also be set to Nullable
and instantiated if not NULL
.
Testing with Rcpp::List
and Rcpp::DataFrame
gives expected results, i.e.,
List is not NULL. List length of 2 elements.
DataFrame is not NULL. DataFrame of 20 rows and 2 columns.
Nullability of RcppGSL::Matrix
In addition to Rcpp
types, RcppGSL::Matrix
can also be set with Nullable
type (e.g, in the
mvlabund
package):
e.g.,
Finally, testing with RcppGSL::Matrix
which can also be set to Nullable<>
, i.e.,
Warning in nullable4(NULL): Input GSL Matrix is NULL.
Input is not NULL. Input GSL matrix has 3 and 3 columns.
Summary
Rcpp
provides a convenient construct to set datatypes to NULL
using R_NilValue
and application
of the datatype if not set to NULL
using the .isNotNull()
check. This construct to applied to
set datatypes to NULL
as default values and possible simple simplification.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.