Does R allow 'Alias'es without Duplicating the Object in question?

Greetings all,
Does R allow for alias-es? I am curious about two different uses.

  1. I would like to have very long name for a variable on a program going to a friend, but I want to use this alias ONLY inside the program, NOT Globally.

    a. I have a large object 'environment' that I don't want to duplicate if I simply rename it.

  2. Next I would like to introduce aliases in my daily use of R. Is using Snippets the best way to do that.
    Cheers,
    M

Aliases don't exist as such with regular variables under normal circumstances. When you do

x <- 1:10 
y <- x
pryr::address(x)
#> [1] "0x7fd0793a01c0"
pryr::address(y)
#> [1] "0x7fd0793a01c0"

y[2] <- 100
pryr::address(x)
#> [1] "0x7fd0793a01c0"
pryr::address(y)
#> [1] "0x7fd07c83a5d8"

y does refer to the same memory—till you do something to modify it, at which point it is copied to a new location in memory ("copy-on-modify" semantics). Trying to keep y from getting copied can be somewhat difficult, so this behavior isn't a full alias system.

There used to be a function called .Alias that created aliases, but it was dropped from R at some point. It's still documented in ?base-defunct, which says

.Alias provided an unreliable way to create duplicate references to the same object. There is no direct replacement. Where multiple references to a single object are required for semantic reasons consider using environments or external pointers. There are some notes on https://developer.r-project.org.

Environments, then, are handled differently—assigning an environment name to a new variable doesn't create a copy, but just a new reference to the same environment:

e <- new.env()
ls(e)
#> character(0)
e    # note memory address
#> <environment: 0x7fd5cdc7f7f0>

e2 <- e

e2$mtcars <- mtcars
ls(e)
#> [1] "mtcars"
e
#> <environment: 0x7fd5cdc7f7f0>
e2
#> <environment: 0x7fd5cdc7f7f0>

?rlang::env explains more explicitly:

Reference semantics

Unlike regular objects such as vectors, environments are an uncopyable object type. This means that if you have multiple references to a given environment (by assigning the environment to another symbol with <- or passing the environment as argument to a function), modifying the bindings of one of those references changes all other references as well.

If you're creating your own class of objects and want reference semantics, R6 may do what you want.

2 Likes