无法使用标量调用 Rcpp 的阶乘函数

Unable to call Rcpp's factorial Function with a Scalar

我在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 ) ) ; }

有人可以帮我解决这个问题吗?谢谢!

问题有两个:

  1. factorial 函数是 VECTORIZED_MATH_1 的一部分,需要 Rcpp::NumericVector 参数。
  2. 您缺少 return 语句。

使用:

Rcpp::cppFunction(
    'Rcpp::NumericVector foo(double t, Rcpp::NumericVector k) {
      Rcpp::NumericVector x = t/factorial(k);
      return x;
    }')