I get "Error: index out of bounds"
when I am using mapply
with a Rcpp function:
R:
mapply(fun, x = totPrimas, y = factorProjec, w = totCurvadf)
x
, y
and z
are data frames with the same dimensions.
Rcpp:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector fun(const NumericVector x, const NumericVector y, const NumericVector w ) {
NumericVector z(x.size());
z(0) = x(0) * y(0);
NumericVector c(x.size());
c(0) = x(0) * w(0);
for(int i = 1; i < x.size(); i++) {
c(i) = (c(i-1) + x(i)) * w(i);
z(i) = c(i) * y(i);
}
return z;
}
Is something wrong in the code? Thanks alot.
As you've noted, the problem was that totCurvadf
was a matrix. The reason this was an issue is that aMatrix[1]
will return a vector of length 1, whereas aDataFrame[1]
will return the first column of the data.frame as a vector of length equal to nrow(aDataFrame)
.
If you did want to do this with matrices (or a mixture of data frames and matrices, you could do:
lapply(1:nrow(totPrimas), function(i) fun(x = totPrimas[, i], y = factorProjec[, i], w = totCurvadf[, i]))