Create function list without eval / parse

I have 3 vectors of equal length y, hand hp, defined as follows:

y  <- c(2, 5, 6)
h  <- c(4, 25, 35)
hp <- c(3, 10, 12)

The values ​​are merely illustrative.

I want to create an output function list final_list in the xfollowing way

function(x) y + (h - hp) * x

(only the perfect illustrative result is displayed):

[[1]]
[1] function(x) 2 + (1) * x

[[2]]
[1] function(x) 5 + (15) * x

[[3]]
[1] function(x) 6 + (23) * x

I know that this can be done using eval / parse, but it does not produce transparent output for functions.

I would like to create functions from these 3 vectors and output without using eval / parse. If possible, I would be very happy to know and be impressed!

+4
source share
3 answers

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)
+4
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
+5

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
+3

Source: https://habr.com/ru/post/1619588/


All Articles