167

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 ()
   }
5
  • 4
    Just curious - why do you need to get object name from an object? Commented Jan 29, 2013 at 7:21
  • 4
    I have a sample use: I have a function that takes as argument a vector, and append the values of that vector into a column in a dataframe. I also need to populate into another column the source of the value, which is the name of the initial vector. Voila. Commented Jan 27, 2015 at 3:46
  • 1
    To use exists() which requires a string. Commented Feb 5, 2017 at 14:08
  • 3
    @ChinmayPatil It may be useful to pass the string name of the object to its output file name, for instance. Commented Apr 11, 2019 at 21:09
  • My two cents: a plotting function using the given variable names as labels / legend Commented Sep 6, 2021 at 7:37

1 Answer 1

319

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

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

myfunc(foo)
[1] "foo"
Sign up to request clarification or add additional context in comments.

8 Comments

@MahdiJadaliha You can try this function: myfunc <- function(v1) { s <- substitute(v1); if (length(s) == 1) deparse(s) else sub("\\(.", "", s[2]) }.
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).
@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.
@SvenHohenstein this doesn't work when you use a for loop...
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
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.