In R, how can I check if two variable names reference the same underlying object?

前端 未结 3 936
抹茶落季
抹茶落季 2020-12-03 07:26

For example:

A <- 1:10
B <- A

Both A and B reference the same underlying vector.

Before I plow off and implement something in

3条回答
  •  佛祖请我去吃肉
    2020-12-03 08:15

    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).

提交回复
热议问题