Rcpp基本数字矩阵示例错误

时间:2014-09-29 17:35:12

标签: r rcpp

我目前正在尝试弄清楚如何使用Rcpp,并且已经浏览了this网站上列出的示例。在涉及矩阵的示例之前,我已经能够完成所有示例。例如,以下代码一直给我带来麻烦。我已将代码分成下面列出的.r文件

# rcpp_test.r     

require( Rcpp )


test<-function(x){

    cppFunction('NumericVector rowSumsC(NumericMatrix x) {

      int nrow = x.nrow(), ncol = x.ncol();

      NumericVector out(nrow);

      for (int i = 0; i < nrow; i++) {

        double total = 0;

        for (int j = 0; j < ncol; j++) {
          total += x(i, j);
        }

        out[i] = total;
      }

      return out;
   }')  

   return(rowSumsC(x))
}

现在,当我执行以下操作时,收到错误消息

> source('rcpp_test.r')
   Loading required package: Rcpp
> x <- matrix(c(1,2,3,4,5,6,7,8,9), byrow=T, nrow=3)
> test(x)
   Error in rowSumsC(x) : 
 INTEGER() can only be applied to a 'integer', not a 'NULL'

不确定这一点:INTEGER()只能应用于&#39;整数&#39;而不是&#39; NULL&#39;因为让NumericMatrix对象工作起来非常酷,所以很容易出错。任何帮助或建议将不胜感激

编辑:

我已经包含了sessionInfo()

> sessionInfo()

R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)

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

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

other attached packages:
[1] Rcpp_0.11.2

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

1 个答案:

答案 0 :(得分:3)

如果我将您的代码放入文件/tmp/rowSumC.cpp

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector rowSumsC(NumericMatrix x) {
  int nrow = x.nrow(), ncol = x.ncol();
  NumericVector out(nrow);

  for (int i = 0; i < nrow; i++) {
    double total = 0;
    for (int j = 0; j < ncol; j++) {
      total += x(i, j);
    }
    out[i] = total;
  }
  return out;
}

然后事情就好了:

R> library(Rcpp)
R> sourceCpp("/tmp/rowSumC.cpp")
R> rowSumsC(matrix(1:9,3))
[1] 12 15 18
R> 

这可能会通过cppFunction()以相同的方式工作,我倾向于保留一行或两行的非常短的函数。