R: Function Definition (original) (raw)
function {base} | R Documentation |
---|
Description
These functions provide the base mechanisms for defining new functions in the R language.
Usage
function( arglist ) expr
\( arglist ) expr
return(value)
Arguments
arglist | empty or one or more (comma-separated) ‘name’ or ‘name = expression’ terms and/or the special token .... |
---|---|
expr | an expression. |
value | an expression. |
Details
The names in an argument list can be back-quoted non-standard names (see ‘backquote’).
If value
is missing, NULL
is returned. If it is a single expression, the value of the evaluated expression is returned. (The expression is evaluated as soon as return
is called, in the evaluation frame of the function and before any[on.exit](../../base/help/on.exit.html)
expression is evaluated.)
If the end of a function is reached without calling return
, the value of the last evaluated expression is returned.
The shorthand form \(x) x + 1
is parsed as function(x) x + 1
. It may be helpful in making code containing simple function expressions more readable.
Technical details
This type of function is not the only type in R: they are called_closures_ (a name with origins in LISP) to distinguish them fromprimitive functions.
A closure has three components, its [formals](../../base/help/formals.html)
(its argument list), its [body](../../base/help/body.html)
(expr
in the ‘Usage’ section) and its [environment](../../base/help/environment.html)
which provides the enclosure of the evaluation frame when the closure is used.
There is an optional further component if the closure has been byte-compiled. This is not normally user-visible, but is indicated when functions are printed.
References
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)The New S Language. Wadsworth & Brooks/Cole.
See Also
[args](../../base/help/args.html)
.
[formals](../../base/help/formals.html)
, [body](../../base/help/body.html)
and[environment](../../base/help/environment.html)
for accessing the component parts of a function.
[debug](../../base/help/debug.html)
for debugging; using [invisible](../../base/help/invisible.html)
insidereturn(.)
for returning invisibly.
Examples
norm <- function(x) sqrt(x%*%x)
norm(1:4)
## An anonymous function:
(function(x, y){ z <- x^2 + y^2; x+y+z })(0:7, 1)
[Package _base_ version 4.6.0 Index]