Jessica B
Jessica B

Reputation: 321

Print out a vector name which is assigned to another vector

Not desperately important, but I would like to print the variable name "v1" using v2:

v1=c(1,2,3,4)
v2=v1
print(source_name(v2))

Can this be done?

Upvotes: 1

Views: 170

Answers (2)

Matthew Plourde
Matthew Plourde

Reputation: 44624

@Rcoster seemed to glean what you were actually requesting, but here's a solution to what your question asks.

# create a callback function that executes at each top level evaluation. 
# If the evaluated call is assignment and the rhs is a symbol, record 
# this in a global variable .source_names, which the function 
# source_name below can reference.
t <- addTaskCallback(function(expr, value, ok, visible) {
    if (class(expr) %in% c('=', '<-')) {
        expr.list <- as.list(expr)
        lhs.index <- 2
        rhs.index <- 3
        if (is.symbol(expr.list[[rhs.index]])) {
            if (! exists('.source_names')) 
                .source_names <<- list()
            .source_names[[as.character(expr.list)[[lhs.index]]]] <<- expr.list[[rhs.index]]
        }
    }
    return(TRUE)
})

source_name <- function(x) {
    name <- deparse(substitute(x))
    if (exists('.source_names')) {
        .source_names[[name]]
    }
}

v1 <- 1
v2 <- v1
source_name(v2)
# v1

# to turn off
removeTaskCallback(t)

Upvotes: 1

Rcoster
Rcoster

Reputation: 3210

You need change v2 to a string and use get(). print() is useless (in this case)

v1=c(1,2,3,4)
v2='v1'
get(v2)

Upvotes: 1

Related Questions