section_fun: Section a function and set default values in function

View source: R/section_fun.R

section_funR Documentation

Section a function and set default values in function

Description

Section a functions domain by fixing certain arguments of a function call.

Usage

set_default(fun, nms, vls = NULL)

section_fun(fun, nms, vls = NULL, method = "def")

section_fun_sub(fun, nms, vls = NULL, envir = parent.frame())

section_fun_env(fun, nms, vls = NULL)

get_section(object)

get_fun(object)

Arguments

fun

Function to be sectioned

nms

Either a named list of the form name=value where each name is the name of an argument of the function (in which case vls is ignored) or a character vector of names of arguments.

vls

A vector or list of values of the arguments

method

"def" (for default); based on substituting fixed values into the function argument list as default values). "env": (for environment); using an auxillary argument for storing sectioned values. "sub": (for substitute); based on substituting fixed values into the function body.

envir

Environment

object

An object from section_fun (a scaffold object).

Details

Let E be a subset of the cartesian product X x Y where X and Y are some sets. Consider a function f(x,y) defined on E. Then for any x in X, the section of E defined by x (denoted Ex) is the set of $y$s in Y such that (x, y) is in E. Correspondingly, the section of f(x,y) defined by x is the function $f_x$ defined on Ex given by $f_x(y)=f(x,y)$.

section_fun is a wrapper for calling set_default (default method), section_fun_env or section_fun_sub. Notice that creating a sectioned function with section_fun_sub can be time consuming.

Value

A new function: The input function fun but with certain arguments fixed at specific values.

Author(s)

Søren Højsgaard, sorenh@math.aau.dk based on code adapted from the curry package.

See Also

bquote_fun_list()

Examples


f  <- function(x, y){x + y}

f_ <- section_fun(f, list(y = 10),    method="def") ## "def"" is default
f_ <- section_fun(f, nms="y", vls=10, method="def") ## SAME AS ABOVE
f_
f_(x=1)

f_ <- section_fun(f, list(y = 10),    method="sub") ## 
f_ <- section_fun(f, nms="y", vls=10, method="sub") ## SAME AS ABOVE
f_
f_(x=1)

f_ <- section_fun(f, list(y = 10),    method="env")
f_ <- section_fun(f, nms="y", vls=10, method="env") ## SAME AS ABOVE
f_
f_(x=1)
get_section(f_)
get_fun(f_)

 
## With more complicated values:
g <- function(A, B) {
  A + B
}
g_ <- section_fun(g, list(A = matrix(1:4, nrow=2)))
g_ <- section_fun(g, "A", list(matrix(1:4, nrow=2)))
g_(diag(1, 2))

g_ <- section_fun(g, list(A = matrix(1:4, nrow=2)))

## Using built in function
set.seed(123)
rnorm5 <- section_fun(rnorm, list(n=5)) 
rnorm5(0, 1)

set.seed(123)
rnorm(5)



doBy documentation built on Nov. 2, 2023, 5:48 p.m.