rnorouzian
rnorouzian

Reputation: 7517

Getting the names of inputted vectors to an R function

I was wondering how I could have my R function foo return the names of the vectors that are inputted to it?

In this example, I want foo to return "a" and "b".

Here is what I tried without success:

a = 1:30 ; b = 50:60   # the inputted vectors

foo <- function(...){  # the function

 L <- list(...)
 names(L)
}

# Example of use:
foo(a, b)

Upvotes: 3

Views: 44

Answers (3)

akrun
akrun

Reputation: 887571

Here is an option with match.call

foo <- function(...) sapply(as.list(match.call())[-1], as.character)
foo(a, b)
#[1] "a" "b"

Upvotes: 0

dww
dww

Reputation: 31452

foo <- function(...) as.character(substitute((...)))[-1]

foo(a, b)
# [1] "a" "b"

Upvotes: 1

G. Grothendieck
G. Grothendieck

Reputation: 269885

Using substitute as shown gives a pairlist of symbols and deparse applied individually to each element converts each to a character string:

foo <- function(...) sapply(substitute(...()), deparse)
foo(a, b)
## [1] "a" "b"

Upvotes: 1

Related Questions