我有3个等长y
,h
和hp
的向量,定义如下:
y <- c(2, 5, 6)
h <- c(4, 25, 35)
hp <- c(3, 10, 12)
这些价值仅仅是说明性的。
我想在final_list
中创建一个输出列表 x
函数,如下所示
function(x) y + (h - hp) * x
(仅显示理想的说明性输出):
[[1]]
[1] function(x) 2 + (1) * x
[[2]]
[1] function(x) 5 + (15) * x
[[3]]
[1] function(x) 6 + (23) * x
我知道这可以通过eval / parse完成,但这不会为函数生成透明输出。
我想从这3个向量创建函数并输出而不使用eval / parse。如果可以的话,我会非常乐意学习并留下深刻的印象!
答案 0 :(得分:5)
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)
输出没有给出您可能期望的但它可以正常工作:
> 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
答案 1 :(得分:4)
您可以将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>
现在让我们调用函数 -
sapply(funs, function(a) a(1))
# [1] 3 20 29
注意:如果您确实需要在函数体中评估这些中间表达式,则可以使用以下代码。
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)
答案 2 :(得分:3)
如果在正确的环境中执行,只需使用function
- 函数就会成功。
> mapply( function(y,h,hp) function(x){ y+(h-hp)*x }, y,h,hp)
[[1]]
function (x)
{
y + (h - hp) * x
}
<environment: 0x7fb570828710>
[[2]]
function (x)
{
y + (h - hp) * x
}
<environment: 0x7fb570823718>
[[3]]
function (x)
{
y + (h - hp) * x
}
<environment: 0x7fb57081b5c8>
> myfuns[[1]](x=1:10)
[1] 3 4 5 6 7 8 9 10 11 12
> 2+(h[1]-hp[1])*1:10
[1] 3 4 5 6 7 8 9 10 11 12
> myfuns[[2]](x=1:10)
[1] 20 35 50 65 80 95 110 125 140 155
这些函数定义(实际上是闭包)中的每一个都带有第一个匹配值,当解释器沿着搜索路径行进时,它们在创建时存在。
> environment(myfuns[[1]])[["y"]]
[1] 2
> environment(myfuns[[1]])[["h"]]
[1] 4
> environment(myfuns[[1]])[["hp"]]
[1] 3