Call functions in C from R

12

I need to optimize some functions that are in the C language, but using the genetic algorithm packages in R.

Is there any way to call C functions in R?

In matlab I know there is this possibility through mex . Does not R have something similar?

    
asked by anonymous 01.07.2015 / 14:16

1 answer

7

I think currently the cleanest and easiest way to integrate C ++ (or C in your case) code is to use Rcpp package (CRAN link) (package website here) .

With Rcpp you can define a function in the section itself using the function cppFunction :

library(Rcpp)
cppFunction('int soma(int x, int y){ 
            int soma = x+y; 
            return soma;
            }')
soma(1,2)
[1] 3

Or you can also define its functions in a .cpp file and use the sourceCpp function. You will specify in the header of the file that you are using Rcpp #include <Rcpp.h> , using namespace Rcpp; and then define its functions. If you are using RStudio, when asking to create a new c ++ file it already gives you the minimum file structure.

#include <Rcpp.h>
using namespace Rcpp;

// This is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp 
// function (or via the Source button on the editor toolbar). Learn
// more about Rcpp at:
//
//   http://www.rcpp.org/
//   http://adv-r.had.co.nz/Rcpp.html
//   http://gallery.rcpp.org/
//

// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
  return x * 2;
}


// You can include R code blocks in C++ files processed with sourceCpp
// (useful for testing and development). The R code will be automatically 
// run after the compilation.
//

/*** R
timesTwo(42)
*/

Well, that's enough to get you started trying to pass the code to R. For more details I recommend the Hadley's book for a more general introduction and package vignettes and the Dirk book for more details about Rcpp.

    
03.07.2015 / 11:06