[Rcpp-devel] How to set a default value when call a R function in Rcpp

Qiang Kou qkou at umail.iu.edu
Fri Nov 11 15:59:35 CET 2016


Hi, Jingyu,

I post a small example below. I think this is what you want.

Best,

KK

#include <Rcpp.h>

using namespace Rcpp;

//[[Rcpp::export]]
void test(Nullable<Function> f = R_NilValue) {
  if (f.isNotNull()) {
    Rcpp::Rcout << "Not NULL fun" << std::endl;
    Function f2(f);
    f2();
  } else {
    Rcout << "NULL fun" << std::endl;
  }
}

/* R code
> Rcpp::sourceCpp("test.cpp")
> f_test <- function() {
+ print("test fun")
+ }
> test(f_test)
Not NULL fun
[1] "test fun"
> test()
NULL fun
*/




On Fri, Nov 11, 2016 at 7:18 AM, Dirk Eddelbuettel <edd at debian.org> wrote:

>
> On 11 November 2016 at 05:53, Jingyu He wrote:
> | 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?
>
> Well that is a different question :) But it has a nice answer: use
>
>    Rcpp::Nullable<Rcpp::Function> rfunction
>
> and test via
>
>    if (rfunction.isNull())
>
> (Untested, but should work)
>
> Dirk
>
> --
> http://dirk.eddelbuettel.com | @eddelbuettel | edd at debian.org
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>



-- 
Qiang Kou
qkou at umail.iu.edu
School of Informatics and Computing, Indiana University
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20161111/94c8a4fb/attachment.html>


More information about the Rcpp-devel mailing list