我在R中定义了一个C++函数,它是:
library(Rcpp)
cppFunction(
'double foo(double t, int k) {
double x = t/factorial(k);
}')
当我在 R 中运行此函数时,收到错误:
file59b051c6b334.cpp:7:25: error: no matching function for call to 'factorial'
NumericVector x = t/factorial(k); ^~~~~~~~~
/Library/Frameworks/R.framework/Versions/3.3/Resources/library/Rcpp/include/Rcpp/sugar/functions/math.h:59:19:
note: candidate function not viable: no known conversion from 'int' to 'SEXP' (aka 'SEXPREC *') for 1st argument VECTORIZED_MATH_1(factorial , ::Rcpp::internal::factorial )
/Library/Frameworks/R.framework/Versions/3.3/Resources/library/Rcpp/include/Rcpp/sugar/block/Vectorized_Math.h:91:9:
note: expanded from macro 'VECTORIZED_MATH_1'
__NAME__( SEXP x){ return __NAME__( NumericVector( x ) ) ; }
有人可以帮我解决这个问题吗?谢谢!
最佳答案
问题有两个方面:
factorial
函数是VECTORIZED_MATH_1
的一部分,需要Rcpp::NumericVector
参数。- 您缺少
return
语句。
用途:
Rcpp::cppFunction(
'Rcpp::NumericVector foo(double t, Rcpp::NumericVector k) {
Rcpp::NumericVector x = t/factorial(k);
return x;
}')
关于r - 无法使用标量调用 Rcpp 的阶乘函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43382942/