Can I avoid the `eval (parse ())` function definition with `polyomial ()` in R?

I want to avoid using the parse()function that contains in the definition polynomial().

My polynomial:

library(polynom)
polynomial(c(1, 2))
# 1 + 2*x   

I want to create a function that uses this polynomial expression, as in:

my.function <- function(x) magic(polynomial(c(1, 2))) 

for where magic()I tried different combinations expression(), formula(), eval(), as.character()and etc .... but nothing works.

My only working solution is using eval(parse()):

eval(parse(text = paste0('poly_function <- function(x) ', polynomial(c(1, 2)))))

poly_function(x = 10) 
# 21

Is there a better way to do what I want? Can i escape eval(parse())?

+4
source share
2 answers

It seems you can easily write your own function too

poly_function = function(x, p){
    sum(sapply(1:length(p), function(i) p[i]*x^(i-1)))
}
# As 42- mentioned in comment to this answer,
# it appears that p can be either a vector or a polynomial

pol = polynomial(c(1, 2))
poly_function(x = 10, p = pol)
#[1] 21

#OR
poly_function(x = 10, p = c(1,2))
#[1] 21
+2
source

, , R, . : :

str(pol)
#Class 'polynomial'  num [1:2] 1 2
help(pac=polynom)

, user20650 :

    > poly_function <- as.function(pol)
    > poly_function(10)
    [1] 21

, (Venables, Hornick, Maechler):

> getAnywhere(as.function.polynomial)
A single object matching ‘as.function.polynomial’ was found
It was found in the following places
  registered S3 method for as.function from namespace polynom
  namespace:polynom
with value

function (x, ...) 
{
    a <- rev(coef(x))
    w <- as.name("w")
    v <- as.name("x")
    ex <- call("{", call("<-", w, 0))
    for (i in seq_along(a)) {
        ex[[i + 2]] <- call("<-", w, call("+", a[1], call("*", 
            v, w)))
        a <- a[-1]
    }
    ex[[length(ex) + 1]] <- w
    f <- function(x) NULL
    body(f) <- ex
    f
}
<environment: namespace:polynom>

, getAnywhere , , , "" . , , :

> as.function
function (x, ...) 
UseMethod("as.function")
<bytecode: 0x7f978bff5fc8>
<environment: namespace:base>

, :

> methods(as.function)
[1] as.function.default     as.function.polynomial*
see '?methods' for accessing help and source code

polynomial , "", .. , . getAnywhere.

+3

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


All Articles