Tyler Rinker
Tyler Rinker

Reputation: 109874

Grabbing object names from within a function

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))
}

Upvotes: 8

Views: 267

Answers (2)

sgibb
sgibb

Reputation: 25736

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"

Upvotes: 6

Arun
Arun

Reputation: 118799

How about this?

grab <- function(x) as.character(x[["foo"]])
FUN <- function(foo, bar=grab(match.call())) { bar }

FUN(mtcars)
# [1] "mtcars"

Upvotes: 6

Related Questions