Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

r - rcpp function calling another rcpp function

I'm guessing this is an easy question, but I'm new to Cpp, and am stuck.

I've created a function in R, using Rcpp and:

// [[Rcpp::export]]

I can call the function in R and it works as intended. Let's call it F1.

Next, I want to create another function, F2, using Rcpp which calls the first function. I use standard function call language (i.e., F1(arguments)), and it compiles fine through R when I use sourceCpp().

But when I try to call F2 in R, I get:

Error in .Primitive(".Call")(

and

F2 is missing

The first .cpp file contains

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double F1(NumericVector a) {
  int n = a.size();
  double result=0;  // create output vector
  double ss = 0;

  for(int i = 0; i < n; ++i) {
    ss += pow(a[i],2);
  }

  result = ss;
  return result;
}

The following is in another .cpp file.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double F2(NumericVector a) {
  double result=0;

  result = F1(a);

  return result;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just put both functions in the same .cpp file, or start working on a package.

If you stick to separate .cpp files, then F2 does not know about F1. You can call back F1 as an R function, but that's not going to be as efficient and you will have to deal with converting outputs to a double, etc ...

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double F2(NumericVector a) {
  double result=0;

  // grab the R function F1
  Function F1( "F1" ) ; 
  result = as<double>( F1(a) );

  return result;
}

But really create a package or put all your functions in the same .cpp file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...