How to convert variable (object) name into String

124,018

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"
Share:
124,018
Danf
Author by

Danf

Updated on January 25, 2020

Comments

  • Danf
    Danf over 4 years

    I have the following data frame with variable name "foo";

     > foo <-c(3,4);
    

    What I want to do is to convert "foo" into a string. So that in a function I don't have to recreate another extra variables:

       output <- myfunc(foo)
       myfunc <- function(v1) {
         # do something with v1
         # so that it prints "FOO" when 
         # this function is called 
         #
         # instead of the values (3,4)
         return ()
       }
    
  • Mahdi Jadaliha
    Mahdi Jadaliha about 9 years
    +1. Thanks for the helpful answer, what about if I pass foo[1]; is there a way to get just "foo" back?
  • Sven Hohenstein
    Sven Hohenstein about 9 years
    @MahdiJadaliha You can try this function: myfunc <- function(v1) { s <- substitute(v1); if (length(s) == 1) deparse(s) else sub("\\(.", "", s[2]) }.
  • theforestecologist
    theforestecologist about 8 years
    How would you do this with multiple objects? Specifically, how would you do it in a way to get separate strings for each object name? (For example, if I had object foo, foo1, and foo2 and I wanted to create a list of their names as separate character strings).
  • Sven Hohenstein
    Sven Hohenstein about 8 years
    @theforestecologist If the function has multiple parameters, you can use deparse(substitute(.)) for each parameter, store the result in a variable, and put the variables in a list afterwards.
  • SumNeuron
    SumNeuron over 7 years
    @SvenHohenstein this doesn't work when you use a for loop...
  • cloudscomputes
    cloudscomputes over 6 years
    you can also use deparse(quote(var)) in which quote freeze the var from evaluation and deparse which is the inverse of parse make the symbol back to string
  • Salix
    Salix over 3 years
    @theforestecologist the best I've found is : unlist(strsplit(gsub("^.*\\(|\\)|\\s","", deparse(substitute(x))), ","))
  • Salix
    Salix over 3 years
    actually see : this and that