【问题标题】:Rcpp function with a double nested 'for' loop returning exception "index out of bounds"具有双重嵌套“for”循环的 Rcpp 函数返回异常“索引超出范围”
【发布时间】:2022-06-13 23:37:22
【问题描述】:

我从一个使用 Rcpp 构建的简单函数中得到错误“索引超出范围”。我需要这个函数来克服它在 R 中运行缓慢的问题。我已经尝试了我所知道的一切来调试这个错误,但我没有成功。该代码使用“tam”行和两列创建矩阵“Resposta”,这些行应该通过循环填充,然后作为我的问题的答案返回。此函数“correlaciona_rcpp”从具有数千行的平方相关矩阵中读取。我只需要获取高于某个值“val”的相关性。因此,有一个带有其行和列名称的向量(因为它是两个相同矩阵之间的相关矩阵,所以行名称和列名称相同)。前面调用此函数的 R 代码将名称向量强制转换为整数向量以简化操作。我尝试使用 srting 向量类型并收到一条类似的错误消息,指出尝试在 SET_STRING ELT 中设置一个比我的“tam”值大两倍的索引。非常欢迎任何帮助。

library(Rcpp)

A=matrix(rnorm(100), 10)

df <- as.data.frame(cor(A,A))
names(df) <-as.character(1:10)

correlaciona <-
  "#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
IntegerMatrix correlaciona_rcpp (NumericMatrix M, IntegerVector nomes, double valor){
  int k = 0;
  int t = nomes.length();
  int tam = nomes.length()*nomes.length();
  IntegerMatrix Resposta(tam, 2);
  for(int i=0; i<t; ++i){
    for(int j=0; i<t; ++j){
      bool l1 = (i != j); 
      bool l2 = (M(i,j)> valor);
      bool l3 =  (M(i,j)==NA_REAL);
      if (l1 & l2 & !l3){
        Resposta ( k , 1 ) = nomes(i);
        Resposta ( k , 2 ) = nomes(j);
        k++;
        
      }
    }
  }
  return(Resposta);
}"

sourceCpp(code = correlaciona)

correlacionar <- function( dtf, val){
  n <- as.integer(names(dtf))
  dtf <- as.matrix(dtf)
  resp <- correlaciona_rcpp( dtf, n, val)
  return(resp)

correlacionar(df, 0.5)

}

【问题讨论】:

  • 我猜i&lt;t 内部的for 循环应该是j&lt;t。投票结束为错字。

标签: c++ r rcpp


猜你喜欢
  • 2013-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
  • 2013-09-28
  • 2019-04-17
相关资源
最近更新 更多