functionabc <- function(api_key, URL, columnNames, globalParam, ...) {
# code
}
My function currently takes in certain values through the ...
(there can be 1 or more). It then stores all of them in a list. I now want to make globalParam
optional with a default value of ""
and I also want the option of having a parameter called valueslist
which would be a list of lists. If the user specifies the value of the parameter valueslist
, the user would not enter multiple values through the ...
This is how I want my function to look...
functionabc <- function(api_key, URL, columnNames, globalParam = "", valueslist = NULL, ...) {
# code
}
How is this function supposed to be called and how do I deal with it? Also, do let me know if there's a better way to do what I am trying to do.
How do you not specify globalParam
and valueslist
, but pass in the ...
set of arguments?
答案 0 :(得分:2)
I think the "optional" parameters, the ones with global defaults, should not impact how you deal with what is passed in the ...
set of arguments. That said, you have to be very careful of R's lazy evaluation and partial argument matching. If you need to combine these and/or ignore the ...
when valueslist=
is defined you could do the following, noting that the valueslist=NULL
appears after the ...
otherwise you end up with the situation where any unnamed argument appearing 5th will be assigned to valueslist
:
functionabc <- function(api_key, URL, columnNames, globalParam="", ..., valueslist=NULL) {
namedlist <- list(
"api_key"=api_key,
"URL"=URL,
"columnNames"=columnNames,
"globalParam"=globalParam
)
if (is.null(valueslist)) {
valueslist <- list(...)
}
print(ls())
flush.console()
list("namedlist"=namedlist, "valueslist"=valueslist)
### code
}
Calling the function like this should all yield logical results, but again, be careful of partial matches in optional, named arguments that you expect to end up in ...
:
functionabc(1,2,3,4,x=5,y=6,z=7)
functionabc(1,2,3,4,5,6,7,8,9)
functionabc(1,2,3,4,5,6,7, valueslist=list(99,100,101))
For example the last yields the following:
> functionabc(1,2,3,4,5,6,7, valueslist=list(99,100,101))
[1] "api_key" "columnNames" "globalParam" "namedlist"
[5] "URL" "valueslist"
$namedlist
$namedlist$api_key
[1] 1
$namedlist$URL
[1] 2
$namedlist$columnNames
[1] 3
$namedlist$globalParam
[1] 4
$valueslist
$valueslist[[1]]
[1] 99
$valueslist[[2]]
[1] 100
$valueslist[[3]]
[1] 101
You might also check to make sure that what's being passed in valueslist
is actually a list object at that stage as well, depending on your needs.