[R] Name the dots! ("...")

Duncan Murdoch murdoch.duncan at gmail.com
Sat Sep 17 14:16:36 CEST 2011


On 11-09-17 5:27 AM, andrewH wrote:
> Dear Folk--
>
> Suppose I have some objects A, B&  C, and a function
> getDots<- function(...) {args<- list(...)  etc.}
>
> If I do a call to getDots(A, B, C) then the variable args will be assigned
> to a list which contains the objects to which A, B&  C refer, but which will
> not (except by happenstance) contain the names A, B, or C.  I would like
> getDots to return a named list, with the object names being assigned as the
> element names in the list.
>
> Is there any way to do this?

Yes, there are two ways.  First, you could name the arguments in the 
call, e.g.

getDots(A=1, B=123, C=5)

and then args will become a named list.  If you want it to happen 
internally, it's harder:  you need to examine the call that was made to 
your function and construct the names from it.

You can do this in a fairly unsatisfactory way as follows:

  values <- list(...)
  names(values) <- lapply( as.list( substitute( list(...) ) )[-1], deparse)

One problem with this is that it will end up with the names "1", "123", 
"5" if you call it as in the example above --- almost certainly not what 
the user would want.

To do it compatibly with data.frame(), just copy the code out of that 
function.  The local variable "vnames" is constructed to hold the column 
names, in about 30 lines of complicated code.

>
> As an aside, I do not understand why the list command does not do this by
> default, like the data.frame command does.  In fact, you can use data.frame
> instead of list to get a named argument list, but only if all your objects
> are of the same length.

data.frames have to have names, lists don't.  Putting those 30 lines of 
code into list() would slow things down unnecessarily.

Duncan Murdoch

>
> Thanks in advance for any help you can offer.
> andrewH
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Name-the-dots-tp3819947p3819947.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list