Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grabbing object names from within a function

Tags:

r

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))
}
like image 546
Tyler Rinker Avatar asked Sep 21 '13 20:09

Tyler Rinker


1 Answers

You could try sys.call to get access to the parent call:

## "which" is the number of the argument of interest
grab <- function(which) {
  ## which + 1, because [1] == name of function/call
  ## and arguments are 2:n
  as.character(sys.call(-1L)[which+1L])
}

FUN <- function(foo, bar = grab(1L)) {
  bar
}

FUN(mtcars)
# "mtcars"
like image 64
sgibb Avatar answered Sep 28 '22 09:09

sgibb