r - r 将带有嵌入函数的 r 函数转换为 Rcpp
问题描述
我有一个 R 函数,其中嵌入了两个 R 函数。
结构是这样的:
f2
是优化的函数,并且optimize
是一个基本 R 函数,它运行f2
多次,直到找到 1 到 5 之间的最小值或最终到达边缘。
R 中的嵌入结构意味着a
计算一次并读入optimize
.
我可以将f1
and转换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)
}
解决方案
我从您的代码中看到的f2
是一个闭包(它使用a
and 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 参数之后给出a
and 。b
interval
解决方案是:
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
;) 中。
推荐阅读
- vue.js - Vue路由器不导航
- sinon - Sinon stub argument return fake callback
- css - How create a sticky Navbar that is changing the color while scrolling? [with Typescript in Angular]
- lighttpd - 阻止对 IP 的请求
- regex - Regex get part from "=" first occurence to left and rest to right
- python - how to take (6+5) as a single input from user in python and display the result
- python - Using recursion and memoization with collatz
- wordpress - 如何使用 Wordpress 设置基于设备的主页?
- azure - 从 VM 中找出 VM 所在的 Azure 区域
- assembly - 在汇编 x86-64 AT&T 中写入内存位置