将Rcpp函数与mapply一起使用时,索引超出范围错误

问题描述 投票:-1回答:1

当我将"Error: index out of bounds"与Rcpp函数一起使用时,我得到mapply

R:

mapply(fun, x = totPrimas, y = factorProjec, w = totCurvadf)

xyz是具有相同尺寸的数据帧。

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;
}

代码有问题吗?非常感谢。

r rcpp
1个回答
1
投票

您已经注意到,问题在于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]))
    
© www.soinside.com 2019 - 2024. All rights reserved.