首页 > 解决方案 > Rcpp NumericVector 类型的正确索引语法是什么?

问题描述

我已经建立了一个过程,它将使用 R 建立一个骰子-索伦森系数的相似矩阵,但是对于需要的循环,它自然运行得非常慢。我正在尝试使用 Rcpp 来实现该解决方案,但我完全坚持使用 c++ 代码引用向量索引,而且我已经将近 7 年没有使用 c++ 并没有帮助。下面代码的预期行为是采用两个具有要比较的值的不同长度的 R 向量(平均大约 5-7 个元素),并将骰子系数的分子计算为整数。向量将填充浮点值(342.02;551.54;等)。我收到“下标值不是数组、指针或向量”的编译错误。我已经看过这个答案,答案,Rcpp 文档和 cplusplus.com 为此事提供任何帮助,但我认为我只需要有人指出我显然遗漏的明显事情。请参阅下面的代码。. .

#include <Rcpp.h>
using namespace Rcpp;
#include <stdio.h>
using namespace std;
#include <cstdlib>

// [[Rcpp::export(name = "diceNumcpp")]]
int diceNum(NumericVector iso1, NumericVector iso2){

  NumericVector is1 = clone(iso1);
  NumericVector is2 = clone(iso2);
  int n = 0;
  int m = 0;
  int match = 0;

  while (is1[n]!=0){      //issue occurs with 'n' reference
    if (is2[m]==0){       //and again here with 'm' reference
      n++;
      m=0;
    }
    if (is1[n]!=0 && is2[m]!=0){  //same issue here with this line and the next
      if (abs(is1[n]-is2[m])/is2[m]<0.01){
        match++;
      }
      m++;
    }
  }
  return match;
}

任何帮助,或对我糟糕的 C++ 的批评,将不胜感激。谢谢!

编辑:

这是一些示例数据。

代码:

iso1 <- c(595.06, 423.02, 321.06)
iso2 <- c(425.01, 321.06)
iso3 <- c(1476, 382.01)

iso1 和 iso2 之间的预期输出 = 2,iso1 和 iso3 之间的预期输出 = 2,以及 iso2 和 iso3 之间的预期输出 = 0

> sessionInfo()
R version 3.6.0 (2019-04-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 16299)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] Rcpp_1.0.3

loaded via a namespace (and not attached):
[1] compiler_3.6.0 tools_3.6.0

标签: c++rcpp

解决方案


推荐阅读