variable scope in c++ function called through R with sourceCpp - r

I have one function nested inside another in R. Since the deeper one is a bit slow, I decided to use sourceCpp to swap in some compiled code. However, that inner function uses variables defined in the outer function. In R I use environments. What's the c++ analog? Do I have to use the extern keyword? Would something like this work?
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
arma::mat myFunc(arma::mat a, arma::mat b){
extern arma::mat c;
return a + b + c;
}

You can pass R environments down to C++ just fine via Rcpp; and examples exists in the docs, here, and in other places. Just randomly tossing a C++ extern in there, however, does access an environment.

Related

Nesting Rcpp functions

Is it possible to nest Rcpp functions in each other?
I have a dummy example right here:
cppFunction(
'int add3(int x) {
return x+3;
}')
cppFunction(
'int add4(int x) {
return add3(x)+1;
}')
add3(2)
This does not work. How can I make this work?
Edit: Okay, so I followed Dirk's advice and now I have a test.cpp file:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
int add3(int x) {
return x + 3;
}
// [[Rcpp::export]]
int add4(int x) {
return add3(x)+1;
}
Which I load in R with sourceCpp("test.cpp"). Now I can use both functions in R and they work although one function calls the other function.
The answers to your question get a little technical quickly, but are all provided in the Rcpp Attributes vignette, and have been for a long time.
First off, you are more-or-less misusing cppFunction(). It is made for quick and simple one-off function tests. Not for writing "infrastructure" or more complex code. For which you should use sourceCpp(), or better still, use a package.
If you switch you code to sourceCpp() and the [[Rcpp::export]] tag you will notice (in verbose=TRUE mode, or in package building) that the exported functions get 'transliterated' into other functions that R calls.
So yes you can nest functions, as you can in C / C++. Nothing is taken from you. But you cannot call the inner, nested function from R but that is possible with the API offered to us by R and which we use (and free you from interfacing directly). It only has SEXP .Call(functionanme, SEXP a, SEXP b,...) as an interface. I.e. a different signature.
But on the C / C++ you can nest, provided you compile your code differently.

Reference to 'internal' is ambiguous when converting to matrix?

I am trying to concert a dataframe to a matrix in rcpp as in this answer: best way to convert DataFrame to Matrix in RCpp
NumericMatrix testDFtoNM(DataFrame x) {
NumericMatrix y = internal::convert_using_rfunction(x, "as.matrix");
return y;
}
and I get the error:
Line 135 reference to 'internal' is ambiguous.
This seems to indicate that there is more than one active namespace with internal as a definition.
How can I find the extra internal and/or how can I fix the code to compile without the error?
Update:
Allan gave me the solution and using Rcpp::inline does allow it to work, but not why and how I can find the correct namespace on my own.
my current namespaces are:
using namespace Rcpp;
using namespace std;
using namespace arma;
using namespace RcppParallel;
Clearly internal exists in more than one of them.
Is there a way to find which references have it without trial and error.
The function you are trying to call is in the internal namespace which is nested inside the Rcpp namespace as you can see in the docs. Presumably you are using at least two namespaces with a nested namespace called internal. Therefore simply specifying
NumericMatrix testDFtoNM(DataFrame x) {
NumericMatrix y = Rcpp::internal::convert_using_rfunction(x, "as.matrix");
return y;
}
should resolve the ambiguity.

Rcpp vs normal C++: header flag available?

I'm a beginner at Rcpp (though with a bit of experience in both R and C++) and am trying to write some code that can be used in both Rcpp and native C++.
As such, I am writing some wrapper functions that return data frames, numeric vectors and the like, that get created from various std containers.
I would like it so that I can set a flag somewhere, or have a flag that automatically detects whether the code is being used in native C++ or Rcpp.
I was wondering whether such a flag exists, or whether I should just go ahead and create one?
Finally, I was wondering whether this was the best way of doing what I wanted to achieve?
EDIT:
This is a very contrived example:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins(cpp11)]]
#include <vector>
#include <functional>
#include <algorithm>
#define RCPP
std::vector<double> multbyTwo(std::vector<double> input) {
std::transform(input.begin(), input.end(), input.begin(), std::bind(std::multiplies<double>(), std::placeholders::_1, 2));
return input;
}
#ifdef RCPP
// [[Rcpp::export]]
NumericVector timesTwo(NumericVector input) {
return wrap(multbyTwo(as<std::vector<double> >(input)));
}
#endif // RCPP
/***R
print(timesTwo(10))
***/
This the kind of thing that I meant - wrapping a pure C++ function with an Rcpp one. (I know there are implicit conversions in this specific case, but there would not be for the kind of function that I would be building)

How to expose a C structure from C library to R with Rcpp

I am trying to expose a C structure from a C library into R. For example:
struct A {
int flag;
// ...
}
It is common that the library provides API to construct and destroy A:
A* initA();
void freeA(A* a);
Thanks for RCPP_MODULE, It is easy to expose it without considering destructor:
#include <Rcpp.h>
using namespace Rcpp;
RCPP_EXPOSED_CLASS(A)
RCPP_MODULE(A) {
class_<A>("A")
.field("flag", &A::flag)
;
}
//'#export
//[[Rcpp::export]]
SEXP init() {
BEGIN_RCPP
return wrap(*initA());
END_RCPP
}
I like this approach, but it might cause memory leak because it does not destruct A properly during garbage collection. Adding .finalizer(freeA) in RCPP_MODULE will cause an error of free twice.
Using XPtr<A, freeA> might be a solution, but I need to manually define functions to expose A.flag.
In general, how do you expose C structure from C library into R with Rcpp?
I suggest you turn your C struct into a C++ class which allows you allocate in the constructor and free in the destructor.
You can still use different ways to have the class transfer easily between R and C++ --- Modules is one of several possibilities.

Code auto-completion trouble with Rcpp and Netbeans/Eclipse

I'm trying to write some Rcpp code using Netbeans, primarily using the IDE for the method look-up / code completion. I've set up the project to include the R/include and R/library/Rcpp/include folders, and it seems this -almost- works. For example, if I write
#include <Rcpp.h>
Rcpp::CharacterVector x;
x. // hit CTRL+SPACE to pop-up methods available to x, no hits
However, if we look at what a CharacterVector is, we see:
typedef Vector<STRSXP> CharacterVector
which is defined in Rcpp/include/vector/instanstiation.h, so it should (?) just be inheriting all the methods available to the Rcpp::Vector class. Equivalently, if I write
Rcpp::Vector<STRSXP> x;
x. // hit CTRL+SPACE, and I do see a bunch of methods available
it does work. Furthermore, if I just copy the typedef declaration into my current source file, then the auto-completion does work.
So, I guess my question is - why does Netbeans struggle in finding the methods available to Rcpp::CharacterVector but not Rcpp::Vector?
Ultimately, it's not a big problem, but I am curious...

Resources