Access to and Manipulation of the Formal Arguments (original) (raw)
formals {base} | R Documentation |
---|
Description
Get or set the formal arguments of a [function](../../base/help/function.html)
.
Usage
formals(fun = sys.function(sys.parent()), envir = parent.frame())
formals(fun, envir = environment(fun)) <- value
Arguments
fun | a function, or see ‘Details’. |
---|---|
envir | environment in which the function should be defined (or found via get() in the first case and whenfun a character string). |
value | a list (or pairlist, hence possiblyNULL) of R expressions. |
Details
For the first form, fun
can also be a character string naming the function to be manipulated, which is searched for in envir
, by default from the parent frame. If it is not specified, the function calling formals
is used.
Only closures, i.e., non-primitive functions, have formals, not primitive functions.
Note that formals(args(f))
gives a formal argument list for all functions f
, primitive or not.
Value
formals
returns the formal argument list of the function specified, as a [pairlist](../../base/help/pairlist.html)
, or NULL
for a non-function or primitive.
The replacement form sets the formals of a function to the list/pairlist on the right hand side, and (potentially) resets the environment of the function, dropping [attributes](../../base/help/attributes.html)
.
See Also
[formalArgs](../../methods/html/methodUtilities.html)
(from methods), a shortcut for names(formals(.))
.[args](../../base/help/args.html)
for a human-readable version, and as intermediary to get formals of a primitive function.[alist](../../base/help/alist.html)
to construct a typical formals value
, see the examples.
The three parts of a (non-primitive) [function](../../base/help/function.html)
are itsformals
, [body](../../base/help/body.html)
, and [environment](../../base/help/environment.html)
.
Examples
require(stats)
formals(lm)
## If you just want the names of the arguments, use formalArgs instead.
names(formals(lm))
methods:: formalArgs(lm) # same
## formals returns a pairlist. Arguments with no default have type symbol (aka name).
str(formals(lm))
## formals returns NULL for primitive functions. Use it in combination with
## args for this case.
is.primitive(`+`)
formals(`+`)
formals(args(`+`))
## You can overwrite the formal arguments of a function (though this is
## advanced, dangerous coding).
f <- function(x) a + b
formals(f) <- alist(a = , b = 3)
f # function(a, b = 3) a + b
f(2) # result = 5
[Package _base_ version 4.6.0 Index]