0

I want to create Rcpp function which input value is R formula. When I use String as an input for a function I get error in R when I writing formula in not string format (if I provide formula like a string in R then all works right). Please provide an example how to use formula class object as an input for Rcpp function.

Will be very greatfull for help!

Bogdan
  • 864
  • 10
  • 18
  • 3
    You can use `Rcpp::Formula` as type of the function argument. What are you trying to do with it at the C++ level? – Ralf Stubner Jul 11 '19 at 09:28
  • Yes, it works, thank you very much for the answer! I am writing package for some econometric models estimation. I found it conveniently to write the package completely in Rcpp. So I extract new dataframe from my dataframe according to the formula (similar to lm function). – Bogdan Jul 11 '19 at 09:39
  • 2
    Interesting. Maybe you can provide a self-answer showing a simple use-case? – Ralf Stubner Jul 11 '19 at 09:49
  • 1
    Okey, I will provide an example! – Bogdan Jul 11 '19 at 09:54

1 Answers1

1

Following Ralf Stubner answer I provide a short example. The function foo takes formula and dataframe as an input argument and returns dataframe which contains variables mentioned in formula.

Rcpp code:

#include <RcppArmadillo.h>
using namespace RcppArmadillo;

//' Extract dataframe from dataframe df according to the formula
//' @export 
// [[Rcpp::export]]
DataFrame foo(DataFrame df, Formula formula)
{
    Rcpp::Environment stats_env("package:stats");
    Rcpp::Function model_frame = stats_env["model.frame"];
    DataFrame df_new = model_frame(Rcpp::_["formula"] = formula, Rcpp::_["data"] = df);
    return(df_new);
}

R code:

my_df <- data.frame("x1" = c(1,2,3), 
                    "x2" = c(4,5,6), 
                    "x3" = c(7,8,9))

my_df_new = foo(df = my_df, formula = x1~x2+I(x3^2)+I(x2*x3))

The output would be:

 x1 x2 I(x3^2) I(x2 * x3)
  1  4      49         28
  2  5      64         40
  3  6      81         54
Bogdan
  • 864
  • 10
  • 18
  • 2
    I'm a bit disappointed that you call `model.frame`. I'd hoped you'd show how to work with formulas in C++. In this example there is no advantage over an R wrapper function. – Roland Jul 11 '19 at 10:48
  • Yes indeed there is no perfomance advantage in my example. However my goal in this case was just to substitute R with Rcpp when formulas are Rcpp function arguments that allows to avoid writing additional R code within Rcpp package. It will be interesting if someone provide C++ specific example. – Bogdan Jul 11 '19 at 10:58