inscaven
inscaven

Reputation: 2584

Rcpp function error Not compatible with STRSXP: [type=NULL]

I'm very new to Rcpp and try to implement a simple thing, but I get an error and don't know what's wrong. I want a function which constructs data.frame from a list. My cpp file looks like this:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
DataFrame makeDF(List x) {
  NumericVector a = x["a"];
  NumericVector b = x["b"];
  NumericVector n = x["n"];
  const int n2 = n[0];

  NumericVector a2 = NumericVector(n2, a[0]);
  NumericVector b2 = NumericVector(n2, b[0]);

  DataFrame df = DataFrame::create(a2, b2);

  return df;
}

Then in R I write:

library(Rcpp)
sourceCpp("./cppcode/check_makeDF.cpp")
# no errors here, it compiles OK
x <- list(a = 2.5, b = 1.1, n = 5)
makeDF(x)
# Error in makeDF(x) :Not compatible with STRSXP: [type=NULL].

Upvotes: 4

Views: 3772

Answers (1)

Ralf Stubner
Ralf Stubner

Reputation: 26823

It works if you name your columns:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
DataFrame makeDF(List x) {
  NumericVector a = x["a"];
  NumericVector b = x["b"];
  NumericVector n = x["n"];
  const int n2 = n[0];

  NumericVector a2 = NumericVector(n2, a[0]);
  NumericVector b2 = NumericVector(n2, b[0]);

  DataFrame df = DataFrame::create(Named("a") = a2, 
                                   Named("b") = b2);

  return df;
}
/*** R
x <- list(a = 2.5, b = 1.1, n = 5)
makeDF(x)
*/

Upvotes: 5

Related Questions