Is (and when) RNGScope scope needed in Rcpp code? - r

When RNGScope scope is needed when using Rcpp? In general, you need it when using C RNG functions. In some places you can read that it is not needed when using Rcpp, examples in Rcpp documentation use it, some examples by Dirk Eddelbuettel use it, while others do not like this one or this do not. So in the end I'm confused...
When exactly is it needed and when not? Does it make a difference if I use Rcpp::runif(), R::runif(), or R::unif_rand()? I'm interested mostly in using Rcpp within R package rather then calling standalone code.

In short:
whenever you call the RNGs of the C API of R, you need to save and later re-set state
RNGScope automates this for you as it is so darn useful (and generally inexpensive)
whenever you use Rcpp Attributes, it inserts RNGScope (as you can see when you turn on verbose=TRUE
So in general you don't need to anything manual -- unless you go really old school and write all code directly, foregoing the glue provided by Rcpp.
And if you use Rcpp, it doesn't matter whether you use scalar interfaces from the R:: namespace or the vectorized Rcpp Sugar onces via Rcpp::. RNGScope will be there for you.

Related

What is the difference between :: and library? [duplicate]

I'm writing some R functions that employ some useful functions in other packages like stringr and base64enc. Is it good not to call library(...) or require(...) to load these packages first but to use :: to directly refer to the function I need, like stringr::str_match(...)?
Is it a good practice in general case? Or what problem might it induce?
It all depends on context.
:: is primarily necessary if there are namespace collisions, functions from different packages with the same name. When I load the dplyr package, it provides a function filter, which collides with (and masks) the filter function loaded by default in the stats package. So if I want to use the stats version of the function after loading dplyr, I'll need to call it with stats::filter.
This also gives motivation for not loading lots of packages. If you really only want one function from a package, it can be better to use :: than load the whole package, especially if you know the package will mask other functions you want to use.
Not in code, but in text, I do find :: very useful. It's much more concise to type stats::filter than "the filter function from the stats package".
From a performance perspective, there is a (very) small price for using ::. Long-time R-Core development team member Martin Maechler wrote (on the r-devel mailing list (Sept 2017))
Many people seem to forget that every use of :: is an R
function call and using it is inefficient compared to just using
the already imported name.
The performance penalty is very small, on the order of a few microseconds, so it's only a concern when you need highly optimized code. Running a line of code that uses :: one million times will take a second or two longer than code that doesn't use ::.
As far as portability goes, it's nice to explicitly load packages at the top of a script because it makes it easy to glance at the first few lines and see what packages are needed, installing them if necessary before getting too deep in anything else, i.e., getting halfway through a long process that now can't be completed without starting over.
Aside: a similar argument can be made to prefer library() over require(). Library will cause an error and stop if the package isn't there, whereas require will warn but continue. If your code has a contingency plan in case the package isn't there, then by all means use if (require(package)) ..., but if your code will fail without a package you should use library(package) at the top so it fails early and clearly.
Within your own package
The general solution is to make your own package that imports the other packages you need to use in the DESCRIPTION file. Those packages will be automatically installed when your package is installed, so you can use pkg::fun internally. Or, by also importing them in the NAMESPACE file, you can import an entire package or selectively importFrom specific functions and not need ::. Opinions differ on this. Martin Maechler (same r-devel source as above) says:
Personally I've got the impression that :: is
much "overused" nowadays, notably in packages where I'd strongly
advocate using importFrom() in NAMESPACE, so all this happens
at package load time, and then not using :: in the package
sources itself.
On the other hand, RStudio Chief Scientist Hadley Wickham says in his R Packages book:
It's common for packages to be listed in Imports in DESCRIPTION, but not in NAMESPACE. In fact, this is what I recommend: list the package in DESCRIPTION so that it’s installed, then always refer to it explicitly with pkg::fun(). Unless there is a strong reason not to, it's better to be explicit.
With two esteemed R experts giving opposite recommendations, I think it's fair to say that you should pick whichever style suits you best and meets your needs for clarity, efficiency, and maintainability.
If you frequently find yourself using just one function from another package, you can copy the code and add it to your own package. For example, I have a package for personal use that borrows %nin% from the Hmisc package because I think it's a great function, but I don't often use anything else from Hmisc. With roxygen2, it's easy to add #author and #references to properly attribute the code for a borrowed function. Also make sure the package licenses are compatible when doing this.

R: When to use package::function() vs function()? [duplicate]

I'm writing some R functions that employ some useful functions in other packages like stringr and base64enc. Is it good not to call library(...) or require(...) to load these packages first but to use :: to directly refer to the function I need, like stringr::str_match(...)?
Is it a good practice in general case? Or what problem might it induce?
It all depends on context.
:: is primarily necessary if there are namespace collisions, functions from different packages with the same name. When I load the dplyr package, it provides a function filter, which collides with (and masks) the filter function loaded by default in the stats package. So if I want to use the stats version of the function after loading dplyr, I'll need to call it with stats::filter.
This also gives motivation for not loading lots of packages. If you really only want one function from a package, it can be better to use :: than load the whole package, especially if you know the package will mask other functions you want to use.
Not in code, but in text, I do find :: very useful. It's much more concise to type stats::filter than "the filter function from the stats package".
From a performance perspective, there is a (very) small price for using ::. Long-time R-Core development team member Martin Maechler wrote (on the r-devel mailing list (Sept 2017))
Many people seem to forget that every use of :: is an R
function call and using it is inefficient compared to just using
the already imported name.
The performance penalty is very small, on the order of a few microseconds, so it's only a concern when you need highly optimized code. Running a line of code that uses :: one million times will take a second or two longer than code that doesn't use ::.
As far as portability goes, it's nice to explicitly load packages at the top of a script because it makes it easy to glance at the first few lines and see what packages are needed, installing them if necessary before getting too deep in anything else, i.e., getting halfway through a long process that now can't be completed without starting over.
Aside: a similar argument can be made to prefer library() over require(). Library will cause an error and stop if the package isn't there, whereas require will warn but continue. If your code has a contingency plan in case the package isn't there, then by all means use if (require(package)) ..., but if your code will fail without a package you should use library(package) at the top so it fails early and clearly.
Within your own package
The general solution is to make your own package that imports the other packages you need to use in the DESCRIPTION file. Those packages will be automatically installed when your package is installed, so you can use pkg::fun internally. Or, by also importing them in the NAMESPACE file, you can import an entire package or selectively importFrom specific functions and not need ::. Opinions differ on this. Martin Maechler (same r-devel source as above) says:
Personally I've got the impression that :: is
much "overused" nowadays, notably in packages where I'd strongly
advocate using importFrom() in NAMESPACE, so all this happens
at package load time, and then not using :: in the package
sources itself.
On the other hand, RStudio Chief Scientist Hadley Wickham says in his R Packages book:
It's common for packages to be listed in Imports in DESCRIPTION, but not in NAMESPACE. In fact, this is what I recommend: list the package in DESCRIPTION so that it’s installed, then always refer to it explicitly with pkg::fun(). Unless there is a strong reason not to, it's better to be explicit.
With two esteemed R experts giving opposite recommendations, I think it's fair to say that you should pick whichever style suits you best and meets your needs for clarity, efficiency, and maintainability.
If you frequently find yourself using just one function from another package, you can copy the code and add it to your own package. For example, I have a package for personal use that borrows %nin% from the Hmisc package because I think it's a great function, but I don't often use anything else from Hmisc. With roxygen2, it's easy to add #author and #references to properly attribute the code for a borrowed function. Also make sure the package licenses are compatible when doing this.

Is it possible to use Alglib with Rcpp?

I often use Rcpp code to incorporate C++ code into R. Through the BH-package I am also able to use the Boost-library. However, the Boost library lacks a function that I would like to use (to be precise, it only has Bessel function but I would like to get Log-Bessel immediately because of overflow). I know that Alglib does have this feature.
Would it be possible to use Alglib with Rcpp, that is, use the log-bessel function from Alglib somehow?
I do not see a clear difference in functionality between the
AlgLib documentation on Bessel functions, and
Boost documentation on Bessel functions.
As such, I think you can just use the BH package giving you all of Boost Math and then some.
Last but not least there is a package bessel on CRAN written by the R Core member focusing on special functions so you could start from there too.

How should I reference functions in imported packages?

When creating an R package, there are at least two alternatives for referencing functions in imported packages.
Either,
Explicitly name the function using the double colon operator whenever you call it, package::function.
Add importFrom(package, function) to the NAMESPACE file, either directly or via an #' #importFrom package function roxygen tag.
What are the advantages and disadvantages of each method?
Are there any technical differences in what each syntax achieves?
Arguments in favour of using package::function
It makes it completely clear where the function has come from.
Arguments in favour of using #importFrom package function
It involves less typing, particularly when a function is used many times by your package.
Since it involves looking up the package and a call to the :: function, package::function has a small runtime performance penalty. See https://stackoverflow.com/a/7283511/134830.
On balance, what's the verdict?
Both methods do the job and arguments either way aren't overwhelming, so don't lose sleep over this. Just pick one method and stick to it.
The policy that has been adopted at my place of work is that for a few commonly used packages, #importFrom roxygen tags should be used. For example, developers are expected to know that ddply comes from plyr, or functions beginning str_ come from stringr. In this case, the explicit parentage of the function isn't as useful to know. For functions outside this core list, (or if there is any ambiguity) :: should be used to make it clear where it came from.

test R extension without R

I have been working on extension to R that is going to do some clustering. The project uses c++ and Rcpp (calculations are performed using RcppArmadillo). As a result I have a few classes I need to test. I was suggested to use googletest. Unfortunately, I fail to run any testing code.
The problem is that in order to test classes that use Rcpp with googletest framework I have to work outside of R environment.
I mean I do not transform data into standard c++ data structures like vector. The dataset is supposed to be enormous. I get NumericMatrix with data and I pass it down. That causes all c++ classes to use Rcpp.h (or armadillo). I wonder if I can use these classes outside of R.
I was looking for any information on standalone programs that use Rcpp as a library but all I get is 'standalone' code as opposite to c++ code compiled directly in R command line interface by inline package. I would prefer to work with googletest because I can test c++ directly.
The question is whether one can use Rcpp without R?
In a strict sense, you can't because Rcpp code is meant to be called from R.
In a wider sense, of course you can provided you write your interfaces correctly. Write C++ code that does not depend on R and Rcpp headers, using just C++ and STL and Armadillo and maybe googletest idioms. Ie do not use Rcpp types such as as Rcpp::NumericMatrix but use Armadillo types such as arma::mat. Test the living daylight out of them. Maybe wrap them up in a library.
Then just write a thin access layer using Rcpp and RcppArmadillo. Et voila -- you have tested code, accessed in R.

Resources