[Rcpp-devel] How to set a default value when call a R function in Rcpp
Jingyu He
jingyu.he at chicagobooth.edu
Fri Nov 11 06:53:57 CET 2016
Hi,
I've deleted the post on StackOverflow. Sorry for the ambiguity, the
problem is not arg, but the Function f.
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
RObject cppfunction(Function rfunction = NULL) {
if( rfunction == NULL){
cout << 1 + 1 << endl; // if we don't pass rfunction to cppfunction,
run something not related to rfunction()
}else{
rfunction() // if we pass rfunction to cppfunction, run it
}
}
rfunction is an argument of cppfunction. Sometimes I need to pass rfunction
to cppfunction sometimes not. So I need to set a default rfunction
(something like NULL indicating not passing it).
But
RObject cppfunction(Function rfunction = NULL)
doesn't work. How can I make it?
Thanks!
Best,
Jingyu
On Thu, Nov 10, 2016 at 11:41 PM Dirk Eddelbuettel <edd at debian.org> wrote:
On 11 November 2016 at 05:16, Jingyu He wrote:
| I'm writing a R package by Rcpp and I have a problem when setting default
value
| when call a R function in Rcpp. Here is an example to pass a R function
to C++,
| provided by http://adv-r.had.co.nz/Rcpp.html
|
| #include <Rcpp.h>
| using namespace Rcpp;
| // [[Rcpp::export]]
| RObject callWithOne(Function f) {
| return f(1);
| }
|
| The question is, how to set the default value for f? I would like to have
the
| choice to pass a function or not, like
|
| callWithOne(Function f = NULL) {
| // if pass f, run f(1)
| // else, run something else
| }
1) Don't crosspost. If you decided to post on StackOverflow, stay on
StackOverflow. Now that you posted here, maybe delete the question on
StackOverflow.
2) I don't understand the question. Wouldn't the following do:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
RObject callWithOne(Function f) {
const int arg = 1;
return f(arg);
}
If it is a constant, as you seem to imply, why not make it one?
But if it is a variable, just pass it down.
Dirk
--
http://dirk.eddelbuettel.com | @eddelbuettel | edd at debian.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20161111/e6a3e1a3/attachment.html>
More information about the Rcpp-devel
mailing list