Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return R's NULL in Rcpp code?

Tags:

null

r

rcpp

Suppose I have a C++ code to compile with Rcpp and will be called in R.

// [[Rcpp::export]]
SEXP to_env(List x) {
  if(x.hasAttribute("names"))
  {
    return x;
  }
  else
  {
    return NULL;
  }
}

What should the NULL value be to return R's NULL instead of a crash?

like image 769
Kun Ren Avatar asked Sep 04 '14 05:09

Kun Ren


People also ask

How to call r function in Rcpp?

Using the Function class, you can call R functions from Rcpp. The argument given to the R function is determined based on position and name. Use Named() or _[] to pass a value to an argument by specifying argument name. Name() can be used in two ways: Named("argument_name", value) or Named("argument_name") = value .

What is return NULL in C?

NULL can be used if a function returns a pointer. In this case, you return an object, which means that you have to return a real, existing object. One way of doing this is to have an "ok" field in the struct that you could set in the init function, and that you could check in the caller.


1 Answers

Use this code:

return R_NilValue;

The same goes for C++ as well as C code; it's part of the R C API.

like image 109
bartektartanus Avatar answered Oct 22 '22 10:10

bartektartanus