Parameter passing in R when interior function arguments are dependent on optional parameters -
i'm working in r , need pass arguments function can used arguments when calling function within original. in example below can see i'm interested in calling interiorfunc() every time primaryfunc() called value of first parameter dependent on existence of second parameter. if declare 'parameter 2' want different set of arguments if don't declare 'parameter 2' in function call. here definition interior function:
interiorfunc(data, resp, param1, param2) { if(missing(param2)) { print(paste("do analysis without parameter 2 on dataset of size",nrow(data),"with response",resp) }else{ print(paste("do analysis parameter 2 on dataset of size",nrow(data),"with response",resp)) } }
and here function calls it:
primaryfunc <- function(dataset, ...) { if(parameter 2 has been declared in call primaryfunc) { results <- interiorfunc(dataset, ...) }else{ modifeddata <- sample(dataset, 2*dataset, replace = true) results <- interiorfunc(modifieddata, ...) } return(results) }
the function call either be:
interiorfuncresults <- primaryfunc(dataset, response, parameter1)
or
interiorfuncresults <- primaryfunc(dataset, response, parameter1, parameter2)
so need determine prior calling interior function if it's 'parameter2' value has been passed in. here definition of interiorfunc() make example reproducible:
thank help.
i think 1 of common strategies filter names,
sub <- function(x, y, param=null, ...){ if(!is.null(param)) message(param, "is being used") else message("not seeing it") } main <- function(a=1, b=2, ..., c=3){ dots <- list(...) if("param" %in% names(dots)) sub(a, b, ...) else sub(a, b, ...) } main(z=2) main(param = 2)
which, of course, assumes ...
receive named arguments.
Comments
Post a Comment