Many R functions take a variable number of arguments. sum() is an example: sum(1, 2), sum(1, 2, 3), and sum(1, 2, 3, 4) are all valid commands.
I need to write scripts that run in batch mode. In these scripts, I need to pass multiple arguments to a function. The arguments will not be passed in from the command line. They must be variables (not strings corresponding to variable names). They will all be of the same class, and their names will start with the same characters, but I won’t know the names or the number of arguments. Is there a succinct way to pass the variables to the function?
Here is an example: I want code the yields the sum of all variables whose names have the pattern ^int\\d$. I know that there is at least one such variable, but I don’t know how many there are. This code works:
# Set up toy data
int1 <- 3
int2 <- 5
# Get the sum
argNames <- ls(pat='^int\\d$')
argNames.list <- as.list(argNames)
argNames.list <- lapply(argNames.list, function (x) get(x))
do.call(sum, argNames.list)
My objection is that this code is a little cumbersome. Spreading the operation out over four lines reduces clarity. Is there an R-idiomatic way to get the same result with fewer lines of code?
(Edited to better address the question)
I don’t think you can do much better than this, which seems pretty minimal to me.