Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain names of variable arguments based on dot dot dot in function R (deparse)

Tags:

r

I am creating an automated plotter, based on some dummy variables. I set it up such that:

plotter <- function(...) { }

will plot all the dummies I feed it.

However, I would like it to be able to add labels to the plot, namely the variable names. I do know that

deparse(substitute(variablename))

will yield

"variablename"

which is a start, but how do I do this in the case of multiple arguments? Is it at possible? Is there a workaround?

like image 254
PascalVKooten Avatar asked Dec 20 '22 05:12

PascalVKooten


1 Answers

names(list(...)) will get you a character vector containing the names of the supplied arguments that have been absorbed by ...:

plotter <- function(...) {names(list(...))}
plotter(x=1:4, y=11:14)
# [1] "x" "y"

Alternatively, if you want to pass in unnamed arguments, try this (which extends @baptiste's now-deleted answer):

plotter <- function(..., pch=16, col="red") {
    nms <- setdiff(as.character(match.call(expand.dots=TRUE)), 
                   as.character(match.call(expand.dots=FALSE)))
    nms
}

x <- 1:4
y <- 1:14
plotter(x, y, col="green")
# [1] "x" "y"
like image 148
Josh O'Brien Avatar answered Jan 12 '23 00:01

Josh O'Brien