Ari B. Friedman
Ari B. Friedman

Reputation: 72769

Getting names from ... (dots)

In improving an rbind method, I'd like to extract the names of the objects passed to it so that I might generate unique IDs from those.

I've tried all.names(match.call()) but that just gives me:

[1] "rbind"         "deparse.level" "..1"           "..2" 

Generic example:

rbind.test <- function(...) {
  dots <- list(...)
  all.names(match.call())
}

t1 <- t2 <- ""
class(t1) <- class(t2) <- "test"
> rbind(t1,t2)
[1] "rbind"         "deparse.level" "..1"           "..2" 

Whereas I'd like to be able to retrieve c("t1","t2").

I'm aware that in general one cannot retrieve the names of objects passed to functions, but it seems like with ... it might be possible, as substitute(...) returns t1 in the above example.

Upvotes: 6

Views: 500

Answers (2)

Tyler Rinker
Tyler Rinker

Reputation: 109984

I picked this one up from Bill Dunlap on the R Help List Serve:

rbind.test <- function(...) {
    sapply(substitute(...()), as.character)
}

I think this gives you what you want.

Upvotes: 13

mnel
mnel

Reputation: 115435

Using the guidance here How to use R's ellipsis feature when writing your own function?

eg substitute(list(...))

and combining with with as.character

rbind.test <- function(...) {
  .x <-  as.list(substitute(list(...)))[-1]
  as.character(.x)
 }

you can also use

rbind.test <- function(...){as.character(match.call(expand.dots = F)$...)}

Upvotes: 8

Related Questions