我有相等长度的3个向量y,h并且hp定义如下:
y <- c(2, 5, 6)
h <- c(4, 25, 35)
hp <- c(3, 10, 12)
Run Code Online (Sandbox Code Playgroud)
这些值只是说明性的.
我想创建一个函数的输出列表 final_list,x如下所示
function(x) y + (h - hp) * x
Run Code Online (Sandbox Code Playgroud)
(仅显示理想的说明性输出):
[[1]]
[1] function(x) 2 + (1) * x
[[2]]
[1] function(x) 5 + (15) * x
[[3]]
[1] function(x) 6 + (23) * x
Run Code Online (Sandbox Code Playgroud)
我知道这可以通过eval/parse完成,但这不会为函数生成透明输出.
我想从这3个向量创建函数并输出而不使用eval/parse.如果可能的话,我会非常乐意学习并留下深刻的印象!
您可以Map()与substitute(). 中间表达式还没有被评估,但我认为这没什么大不了的。它们将在调用函数时进行评估。基本上我们只是将功能组装成部分。
funs <- Map(
function(a, b, c) {
f <- function(x) x
body(f) <- substitute(y + (h - hp) * x, list(y = a, h = b, hp = c))
f
},
a = y, b = h, c = hp
)
funs
# [[1]]
# function (x)
# 2 + (4 - 3) * x
# <environment: 0x4543fd0>
#
# [[2]]
# function (x)
# 5 + (25 - 10) * x
# <environment: 0x4549e20>
#
# [[3]]
# function (x)
# 6 + (35 - 12) * x
# <environment: 0x454e5d8>
Run Code Online (Sandbox Code Playgroud)
现在让我们调用函数 -
sapply(funs, function(a) a(1))
# [1] 3 20 29
Run Code Online (Sandbox Code Playgroud)
注意:如果你真的需要在函数体中计算那些中间表达式,你可以使用以下代码代替。
make <- function(a, b, c) {
d <- b - c
f <- function(x) x
body(f) <- substitute(y + (e) * x, list(y = a, e = d))
f
}
funs <- Map(make, y, h, hp)
Run Code Online (Sandbox Code Playgroud)
y <- c(2,5,6)
h <- c(4, 25, 35)
hp <- c(3, 10, 12)
fun_create <- function(y, h, hp){
fun <- function(x){y + (h - hp)*x}
return(fun)
}
out <- mapply(y, h, hp, FUN = fun_create)
Run Code Online (Sandbox Code Playgroud)
输出没有给出你可能期望但它正常工作:
> out
[[1]]
function (x)
{
y + (h - hp) * x
}
<environment: 0x282ee40>
[[2]]
function (x)
{
y + (h - hp) * x
}
<environment: 0x282e610>
[[3]]
function (x)
{
y + (h - hp) * x
}
<environment: 0x282dde0>
> out[[1]](1)
[1] 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |