For example:
A <- 1:10
B <- A
Both A and B reference the same underlying vector.
Before I plow off and implement something in
I found this question when looking for a function that checks whether a single variable is referenced at all, especially in the context of data.table. Extending the other answers, I believe the following function does this:
is_referenced <- function(x) {
nom <- as.character(substitute(x))
ls_ <- ls(parent.frame())
ls_ <- ls_[ls_ != nom]
tr <- tracemem(x)
for (i in ls_) {
if (identical(x, get(i, envir = parent.frame()))) {
if (identical(tr, tracemem(get(i, envir = parent.frame())))) {
untracemem(x)
untracemem(get(i, envir = parent.frame()))
print(i)
return(TRUE)
} else {
untracemem(get(i, envir = parent.frame()))
}
}
}
untracemem(x)
FALSE
}
x <- 1:10
y <- x
is_referenced(x)
#> [1] "y"
#> [1] TRUE
z <- 1:10
is_referenced(z)
#> [1] FALSE
y[1] <- 1L
is_referenced(y)
#> [1] FALSE
library(data.table)
DT <- data.table(x = 1)
ET <- DT
is_referenced(DT)
#> [1] "ET"
#> [1] TRUE
is_referenced(ET)
#> [1] "DT"
#> [1] TRUE
ET[, y := 1]
is_referenced(DT)
#> [1] "ET"
#> [1] TRUE
DT <- copy(ET)
is_referenced(DT)
#> [1] FALSE
Created on 2018-08-07 by the reprex package (v0.2.0).