The title isn't super descriptive as the problem is longer than a reasonable title I could think of could display.
I want to have a function that grabs object names from other functions that can be used as arguments in another function. Here's a barebones attempt:
grab <- function(x) {
as.character(substitute(x))
}
FUN <- function(foo, bar = grab(foo)) {
bar
}
FUN(mtcars)
Here I's want FUN
to return the character string "mtcars" but it returns "foo". How could a make a grab function that does this (I want to do this because I'm going to use this as the default to a txt/csv etc file. It's a convenience setting.
Here are some unsuccessful attempts (but I want to have a generic grab function):
FUN2 <- function(foo, bar = as.character(substitute(bar))) {
bar
}
FUN2(mtcars)
#==================
FUN3 <- function(foo, bar) {
if(missing(bar)) bar <- foo
as.character(substitute(bar))
}
FUN3(mtcars)
Real life-ish example:
real_example <- function(obj, file = grab(obj)) {
write.csv(obj, file = sprintf("%s.csv", file))
}