当我将"Error: index out of bounds"
与Rcpp函数一起使用时,我得到mapply
:
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;
}
代码有问题吗?非常感谢。
您已经注意到,问题在于totCurvadf
是矩阵。这是一个问题,其原因是aMatrix[1]
将返回长度为1的向量,而aDataFrame[1]
将作为长度等于nrow(aDataFrame)
的向量返回data.frame的第一列。
如果您确实想对矩阵(或数据帧和矩阵的混合,则可以这样做:
lapply(1:nrow(totPrimas), function(i) fun(x = totPrimas[, i], y = factorProjec[, i], w = totCurvadf[, i]))