好吧,所以我在R编程,我想制作一个C ++函数。我已经导入了Rcpp和内联库。现在,我只是想创建一个添加2个数字的简单函数,但无论我尝试什么,都会出错。
这是我的代码:
cppstring = 'double ss = RcppSexp(s).asDouble(); return RcppSexp(ss+4).asSexp();'
hi <- cfunction(body=cppstring, signature(s="double"), Rcpp = TRUE)
当我进入第二行时,我得到了
file628a34ce.cpp: In function ‘SEXPREC* file628a34ce(SEXPREC*)’:
file628a34ce.cpp:9: error: ‘RcppSexp’ was not declared in this scope
make: *** [file628a34ce.o] Error 1
ERROR(s) during compilation: source code errors or compiler configuration errors!
Program source:
1: #include <Rcpp.h>
2:
3:
4: extern "C" {
5: SEXP file628a34ce ( SEXP s );
6: }
7:
8: SEXP file628a34ce ( SEXP s ) {
9: double ss = RcppSexp(s).asDouble(); return RcppSexp(ss+4).asSexp();
10: Rf_warning("your C program does not return anything!");
11: return R_NilValue;
12: }
Error in compileCode(f, code, language, verbose) :
Compilation ERROR, function(s)/method(s) not created! file628a34ce.cpp: In function ‘SEXPREC* file628a34ce(SEXPREC*)’:
file628a34ce.cpp:9: error: ‘RcppSexp’ was not declared in this scope
make: *** [file628a34ce.o] Error 1
我已经尝试了所有我能想到的东西,从转换到移动代码,到#including RcppSexp,再到简单的返回s,每次我得到一些错误,无论是
cannot convert ‘double’ to ‘SEXPREC*’ in return
或
invalid use of undefined type ‘struct SEXPREC’
或
forward declaration of ‘struct SEXPREC’
......我很困惑:(我在网上看过几个例子,我现在看到的似乎是其他人都在做的事情,它对他们来说神奇地起作用......
这个SEXPREC *我到处都看到了什么?那它是什么外部“C”功能呢?为什么它会在我的return语句之后生成语句并告诉我我的函数不会返回任何内容,即使它确实存在?
答案 0 :(得分:8)
你有没有理由不使用内联的(字面意思!!)数十个Rcpp示例?
另外,RcppSexp到底是什么?你有哪些文件?
以下是我昨晚为rcpp-devel(您应该加入)的人做的一个例子:
library(Rcpp)
library(inline)
xorig <- c(1, -2, 3, -4, 5, -6, 7)
code <- '
Rcpp::NumericVector x(xs);
Rcpp::NumericVector xa = sapply( x, ::fabs );
return(xa);
'
xabs <- cxxfunction(signature(xs="numeric"),
plugin="Rcpp",
body=code)
xabs(xorig)
这是一个更高级的例子,因为它使用 Rcpp sugar 在C ++中为我们提供了矢量化表达式 a la R ,我们在这里用简单的{{1来自 Rcpp sugar :
sapply()
这最清楚地展示了您的两个要求:我们使用隐式模板转换器R> library(Rcpp)
R> library(inline)
R>
R> xorig <- c(1, -2, 3, -4, 5, -6, 7)
R>
R> code <- '
+ Rcpp::NumericVector x(xs);
+ Rcpp::NumericVector xa = sapply( x, ::fabs );
+ return(xa);
+ '
R>
R> xabs <- cxxfunction(signature(xs="numeric"),
+ plugin="Rcpp",
+ body=code)
R>
R> xabs(xorig)
[1] 1 2 3 4 5 6 7
R>
从R中给出的as<>()
转到初始向量,然后使用隐式模板转换器SEXP
返回已转换的第二个向量。
所有这些都在Rcpp介绍插图和Rcpp文档中的其他插图中详细解释。