How to get the name of an object in R

I'm having trouble with something simple and need some help.

I'm writing a function that should print the name of the object but can't seem to get it to work.

The issue I'm having is that I can't get the name of the object printed inside of the function.
See code below:

func_ <- function(x) {
  print(quote(x))
}
func_(mtcars)

The result of this function is "x" and not "mtcars".

How do I change the function to print "mtcars" or the name of any other object that I pass to x?

You can use substitute()

func_ <- function(x) {
  print(substitute(x))
}
func_(mtcars)
#> mtcars

Created on 2019-12-12 by the reprex package (v0.3.0.9001)

6 Likes

Fantastic!!

Thank you!!!!!!:see_no_evil:

Hi,

One question, shouldn't you wrap the substitute in an as.character to get the output as a string?

func_ <- function(x) {
  print(as.character(substitute(x)))
}
func_(mtcars)
[1] "mtcars"

PJ

4 Likes

Yes! Good call. I forgot that part!

It works without the as.character()

Yeah, but you could then go on to evaluate it, which you might want (or not). But, if you're trying to return a string, I'd go with the as.character() wrapper.

Thanks I’ll make that change

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.