Reputation: 31452
I would like to pass a data.frame as argument to Rcpp function with optional columns. The c++ function then needs to test whether the columns exist or not. If I use the sugar function any
as in the following example, I get a compilation error.
cppFunction(
'double test(DataFrame test_data) {
double x=NA_REAL;
CharacterVector colnames = CharacterVector::create("foo");
CharacterVector df_names = test_data.names();
if (any(df_names == colnames)) x = 1.0;
return(x);
}')
invalid use of incomplete type class Rcpp::sugar::forbidden_conversion`
I know I can test the character values one by one in a loop, like this (which works as expected):
cppFunction(
'double test(DataFrame test_data) {
double x=NA_REAL;
CharacterVector colnames = CharacterVector::create("foo");
CharacterVector df_names = test_data.names();
for (int i=0; i<df_names.length(); i++) {
if (df_names[i] == colnames[i]) x = 1.0;
}
return(x);
}')
test(data.frame(bar=3))
# [1] NA
test(data.frame(foo=3))
# [1] 1
But, I would like to use a vectorised "sugar" version if this is possible. What am I doing wrong, and how do I do that?
Upvotes: 0
Views: 116
Reputation: 41220
You could add is_true
to return a boolean:
library(Rcpp)
cppFunction(
'double test(DataFrame test_data) {
double x=NA_REAL;
CharacterVector colnames = CharacterVector::create("foo");
CharacterVector df_names = test_data.names();
if (is_true(any(df_names == colnames))) x = 1.0;
return(x);
}')
Upvotes: 5