Home > Enterprise >  Function to return function of product of vector elements
Function to return function of product of vector elements

Time:11-07

For a given vector of nodes, e.g., nodes = 1:5 I would like the function prod_x to return a function in x of the form
f(x) = (x−1) * (x−2) * (x−3) * (x−4) * (x−5)

prod_x <- function(nodes){
    out <- prod(x - nodes)
    return(out)
}

I tried writing a reprex of what I expect below, but it does not work as intended.

Test out the function on a sample set of node values 1:5

NODES <- 1:5
z <- prod_x(nodes = NODES)
#> Error in prod_x(nodes = NODES): object 'x' not found

Expect this to return a function but returns 0 value

z 
#> Error in eval(expr, envir, enclos): object 'z' not found

z(0) Should produce -120, i.e. -factorial(5) in this case.

That is, z(0) = (0 - 1)*(0 - 2)*(0 - 3)*(0 - 4)*(0 - 5)

z(0)
#> Error in z(0): could not find function "z"

Created on 2021-11-06 by the reprex package (v2.0.1)

As it can be seen the above approach does not work as intended. Could anyone explain how to make it work, and in a vectorized manner?

CodePudding user response:

Right now you are not returning a function. In order to create a new function, you should see the function keyword. That's where you define the parameters as well. It should look like

prod_x <- function(nodes){
  function(x) {
    prod(x - nodes)
  }
}

This will work fine for one x but prod() will collapse multiple values of x into one result. If you want your function to be vectorized over x, then you could also add

prod_x <- function(nodes){
  Vectorize(function(x) {
    prod(x - nodes)
  })
}
  • Related