r 将具有嵌入式函数的 r 函数转换为 Rcpp

r convert an r function with an embedded function into Rcpp

我有一个 R 函数,其中嵌入了两个 R 函数。

结构是这样的:

R中的embedding结构是指a计算一次,读入optimize.

我可以将 f1f2 转换为 Rcpp 函数并将优化函数导入 Rcpp。

但是当我将 f2cpp 版本放入 f1 的 Rcpp 版本中时,我收到一条错误消息,指出不允许这种类型的嵌入。

我意识到这不是一个可重现的例子。我不知道如何在堆栈溢出中搜索这种类型的构造,所以我正在寻找有关如何找到正确方法的提示。

f1 <- function(x, y, z) {
     a <- x + y
     b <- x + b
     f2 <- function(z) {
         d <- z + a + b
     }
     out <- optimize(f2, c(1, 5))
     return(out)
}

我从你的代码中看到 f2 是一个闭包(它使用 ab,但参数列表中没有它们)。 假设的原因是 - 我猜 - 因为你认为 optimize 需要一个单子函数(一个只有一个参数的函数)来 optimize 结束。但事实并非如此。

here in the documentation:

optimize(f, interval, …, lower = min(interval), upper = max(interval), maximum = FALSE, tol = .Machine$double.eps^0.25)

optimise(f, interval, …, lower = min(interval), upper = max(interval), maximum = FALSE, tol = .Machine$double.eps^0.25)

与:

f                  the function to be optimized. 
                   The function is either minimized or maximized over 
                   its first argument depending on the value of maximum.
interval           a vector containing the end-points of the interval to be searched for the minimum.
…                  additional named or unnamed arguments to be passed to f.
lower              the lower end point of the interval to be searched.
upper              the upper end point of the interval to be searched.
maximum            logical. Should we maximize or minimize (the default)?
tol                the desired accuracy.

所以你可以在 interval 之后给出 ab 作为参数。

解决方法是:

f2 <- function(z, a, b) {
     d <- z + a + b
     return(d)
}


f1 <- function(x, y, z) {
     a <- x + y
     b <- x + b
     out <- optimize(f2, c(1, 5), a, b)
     return(out)
}

但在 Rcpp ;) .