alias {aka} | R Documentation |
Create an alias for an expression
Description
alias(name = expr
) creates an alias for expr
named name
. Subsequently, name
can (mostly) be used interchangeably with expr
.
name %&=% expr
is the same as alias(name = expr)
.
Usage
alias(name = expr, expr_env = parent.frame(), alias_env = parent.frame())
name %=&% expr
Arguments
expr_env |
the environment in which to evaluate the expression |
alias_env |
the environment in which to create the alias |
name |
the alias name |
expr |
an arbitrary R expression to be aliased by |
Details
After executing alias(name = expr)
, name
can be used to refer to the value of expr
. This is especially useful when expr
is a complex expression that is used multiple times in the code. Unlike with regular assignment, expr
will be reevaluated every time name
is evaluated. This means that the value of name
always stays up to date, similar to a “reactive” expression. On the flip side, it also means that accessing name
can be very slow if evaluating expr
is time-consuming.
expr
can contain interpolated expressions using the bquote()
syntax (including splicing). These will be substituted at the time of defining the alias. See Examples.
The parameters expr_env
and alias_env
are used to control the environments in which the expression is evaluated and the alias is created, respectively. Note that specifying the correct expr_env
is particularly important when assigning to an alias: an expression can be evaluated inside a parent environment without having to specify expr_env
; however, during assignment this would cause the assignee object to be copied into the calling environment. See Examples for a concrete example of this.
Value
alias()
is called for its side-effect and does not return a value.
Examples
x = 'hello'
alias(ax = x)
ax # prints 'hello'
x = 'world'
ax # prints 'world'
ax = 'goodbye'
x # prints 'goodbye'
# Aliases can be created for complex expressions:
alias(mercedes = mtcars[grepl('^Merc ', rownames(mtcars)), ])
mercedes
mercedes$vs = 0 # set all Mercedes engine types to V-shaped
mtcars
# Aliases can contain interpolated expressions:
n = 1
m = 2
alias(s = .(n) + m)
s # prints 3
n = 10
m = 10
s # prints 11
alias_expr('s') # prints `1 + m`
# Be careful when assigning to an alias to an object in a parent environment:
e = attach(new.env())
e$y = 'hello'
alias(ay = y)
# Works: `y` is found in the parent environment
ay # prints 'hello'
# But the following creates a *new variable* `y` in the current environment:
ay = 'world'
e$y # prints 'hello', still!
y # prints 'world'
# To prevent this, use `expr_env`:
# alias(ay = y, expr_env = e)