I have two functions that are conceptually like the two below. The first one builds a model with a set of parameters. The second one builds all models with 4 parameters held constant and one supplied in a list.
build_one_model <- function(a, b, x, c, d) {
a + b + x + c + d
}
build_all_models <- function(a, b, xList, c, d) {
lapply(xList, function(x) build_one_model(a, b, x, c, d))
}
Example usage:
xList <- list(1, 2, 3)
build_all_models(1, 2, xList, 4, 5)
[[1]]
[1] 13
[[2]]
[1] 14
[[3]]
[1] 15
Now I can convert build_one_model()
to Rcpp
:
#include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
double build_one_model(double a, double b, double x, double c, double d) {
return a + b + x + c + d;
}
But how can I convert build_all_models()
? lapply()
only takes one input, and mapply()
takes up to three, but I have 5.
I think I can settle with a for
loop. I have to remind myself that I'm in C++ and not R, so for
loops are not bad.
#include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
double build_one_model(double a, double b, double x, double c, double d) {
return a + b + x + c + d;
}
//[[Rcpp::export]]
List build_all_models(double a, double b, List xList, double c, double d) {
Rcpp::List ans(xList.length());
for (int i = 0; i < xList.length(); i++) {
ans[i] = build_one_model(a, b, xList[i], c, d);
}
return ans;
}
xList <- list(1, 2, 3)
build_all_models(1, 2, xList, 4, 5)
[[1]]
[1] 13
[[2]]
[1] 14
[[3]]
[1] 15