Reputation: 914
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!
Upvotes: 0
Views: 292
Reputation: 914
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
Upvotes: 1