当我使用带有Rcpp函数的mapply时,我得到“Error:index out of bounds”:
R:
mapply(fun, x = totPrimas, y = factorProjec, w = totCurvadf)
x,y和z是具有相同尺寸的数据框。
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;
}
代码中有问题吗?非常感谢。
答案 0 :(得分:1)
正如您所指出的,问题是totCurvadf
是一个矩阵。这是一个问题的原因是aMatrix[1]
将返回长度为1的向量,而aDataFrame[1]
将返回data.frame的第一列作为长度等于nrow(aDataFrame)
的向量。
如果您确实想要使用矩阵(或混合数据框和矩阵),您可以这样做:
lapply(1:nrow(totPrimas), function(i) fun(x = totPrimas[, i], y = factorProjec[, i], w = totCurvadf[, i]))