首页 > 解决方案 > r 将带有嵌入函数的 r 函数转换为 Rcpp

问题描述

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

结构是这样的:

R 中的嵌入结构意味着a计算一次并读入optimize.

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

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

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

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)
}

标签: rmathematical-optimization

解决方案


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

在文档中查看此处:

优化(f,间隔,...,下 = min(间隔),上 = max(间隔),最大值 = FALSE,tol = .Machine$double.eps^0.25)

优化(f,间隔,...,下 = min(间隔),上 = max(间隔),最大值 = 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.

所以你可以在as 参数之后给出aand 。binterval

解决方案是:

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;) 中。


推荐阅读