Rcpp基本数值矩阵示例错误

Rcpp基本数值矩阵示例错误,r,rcpp,R,Rcpp,我目前正试图弄清楚如何使用Rcpp,并且已经浏览了网站上列出的示例。我能看完所有的例子,直到涉及矩阵的例子。例如,下面的代码一直给我带来麻烦。我已将代码分离到下面列出的.r文件中 # rcpp_test.r require( Rcpp ) test<-function(x){ cppFunction('NumericVector rowSumsC(NumericMatrix x) { int nrow = x.nrow(), ncol = x.nco

我目前正试图弄清楚如何使用Rcpp,并且已经浏览了网站上列出的示例。我能看完所有的例子,直到涉及矩阵的例子。例如,下面的代码一直给我带来麻烦。我已将代码分离到下面列出的.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))
}

如果我将您的代码放入文件
/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;
}

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

这段代码为我运行,您可以发布您的
sessionInfo()
?我也没有收到任何错误。你有没有试过不带着它跑步?就在你在全局环境中定义了这个函数之后?是的,我刚刚试过,得到了同样的错误。也许RStudio有问题,或者我使用的Rcpp版本太新了。我两天前刚刚下载了所有内容(即R Studio,Rcpp)。我有相同的Rcpp版本,所以不是它。可能尝试关闭并重新打开,然后从新会话运行此。否则我就没主意了,很幸运那没用。我希望事情就这么简单!这看起来可能会让我有一段时间不舒服,我在Windows环境中仍然会遇到同样的错误,但是因为其他人都说同样的代码可以工作,所以我在Mac上尝试了一下,结果成功了!这可能是窗户的东西。哦,好吧,从现在起,我将在类似Unix的环境中工作。谢谢
> 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
#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>