as.function.formula: Make a one-line function from a formula.

Description Usage Arguments Value Note See Also Examples

View source: R/fn.R

Description

Create a function from a formula.

Usage

1
2
## S3 method for class 'formula'
as.function(x, ...)

Arguments

x

Formula with no left side.

...

Currently not used.

Value

A function is returned whose formal arguments are the variables in the left hand side, whose body is the expression on the right side of the formula and whose environment is the environment of the formula. If there is no left hand side the free variables on the right, in the order encountered are used as the arguments. letters, LETTERS and pi are ignored and not used as arguments. If there is no left hand side and any of ..1, ..2, ..., ..9 are found as free variables then they are not used as arguments but ... is used as a trailing argument instead. If there is no left hand side and `&` is found as a free variable then that variable is used as the first argument and ... is added as the last argument. If the left hand side is 0 then the function is created as a zero argument function.

Note

->, ->>, =, <-, <<- and ? all have lower operator precdence than ~ so function bodies that contain them typically must be surrounded with {...}.

See Also

Syntax.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
old.options <- options(keep.source = FALSE)
as.function(~ as.numeric(x) + as.numeric(y))
as.function(x + y ~ as.numeric(x) + as.numeric(y)) # same
as.function(~ ..1 + ..2)
# the replacement function in gsubfn uses as.function.formula to
# interpret formulas as functions.  Here we insert ! after each digit.
gsubfn("[0-9]", ~ paste0(`&`, "!"), "ab4cd5") 
## Not run: 
# example where function body must be surrounded with {...} 
# due to use of <<-.  See warning section above.
assign("mywarn", NULL, .GlobalEnv)
fn$tryCatch( warning("a warning"), 
    warning = w ~ { mywarn <<- conditionMessage(w)})
print(mywarn)

## End(Not run)
options(old.options)

gsubfn documentation built on May 1, 2019, 8:50 p.m.