Dawie
December 12, 2019, 1:49pm
1
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?
mara
December 12, 2019, 2:03pm
2
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
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
mara
December 12, 2019, 2:08pm
6
Yes! Good call. I forgot that part!
Dawie
December 12, 2019, 2:44pm
7
It works without the as.character()
mara
December 12, 2019, 2:59pm
8
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.
Dawie
December 12, 2019, 4:13pm
9
Thanks I’ll make that change
system
Closed
January 2, 2020, 4:13pm
10
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.