as_fun: Convert object to function

Description Usage Arguments Value Author(s) See Also Examples

View source: R/as_fun.R

Description

as_fun is a generic function that does the same as as.function from package base, with the additional feature that as_fun.character converts a string into the function it names.

Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
as_fun(x, ...)

as.fun(x, ...)

## Default S3 method:
as_fun(x, envir = parent.frame(), ...)

## S3 method for class 'character'
as_fun(x, ...)

## S3 method for class 'formula'
as_fun(x, ...)

## S3 method for class 'name'
as_fun(x, ...)

## S3 method for class 'call'
as_fun(x, ...)

## S3 method for class 'numeric'
as_fun(x, ...)

## S3 method for class 'logical'
as_fun(x, ...)

## S3 method for class 'factor'
as_fun(x, ...)

## S3 method for class 'complex'
as_fun(x, ...)

## S3 method for class 'data.frame'
as_fun(x, ...)

## S3 method for class 'lm'
as_fun(x, ...)

## S3 method for class 'rpart'
as_fun(x, ...)

Arguments

x

The object to convert.

...

Additional arguments (currently not used).

envir

Environment in which the function should be defined.

Value

The desired function.

Author(s)

as_fun.character is adapted from MrFlick, see https://stackoverflow.com/a/38984214 on StackOverflow.

See Also

as_function in package rlang.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
as_fun(mean)
as_fun("mean")
as_fun("edit")
as_fun("stats::predict")

## Uses 'rlang::as_function()' for formulas under the hood: 
f <- as_fun(~ . + 1)
f(10) # 11

## the constant function '1'
f <- as_fun(1)
f(2)   # 1
f("a") # 1

## the constant function 'FALSE'
f <- as_fun(FALSE)
f(2)   # FALSE
f("a") # FALSE

f <- as_fun(data.frame(x = 1:2, y = 2:3))
f("x") # 'x' column
f("y") # 'y' column

paulponcet/bazar documentation built on July 15, 2019, 5:28 a.m.