x = 'hello'
alias(ax = x) # same as: ax := x
ax # prints 'hello'
x = 'world'
ax # prints 'world'
ax = 'goodbye'
x # prints 'goodbye'
# Aliases can be created for complex expressions:
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
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'
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 the `expr_env` argument:
# alias(ay = y, expr_env = e)
# \dontshow{
# cleanup
detach()
# }
Run the code above in your browser using DataLab