I have a problem where I'm trying to pass a list of arguments to a custom function, but I want the first part of the function to check if certain arguments are NULL, and then assign the value of zero if that is true. I've found a similar question here, but it isn't helping me figure out my particular problem. I'm trying to pass 4 arguments (aa, bb, dd, and ff) to the function, and then check if cc and ee are NULL. If so, then I want to first part of the function to define the NULL values (cc and ee in this case) as zero. I think the problem lies in unpacking, or unlisting x so that the function recognizes the arguments that are being passed.
Consider the following code:
test <- list(aa = 2, bb = 0.5, dd = 2, ff = 16)
testfunc <- function(x, aa=NULL, bb=NULL, cc=NULL, dd=NULL, ee=NULL, ff=NULL) {
unlist(x, recursive = TRUE, use.names = TRUE)
if(!is.null(aa)) aa <- 0
if(!is.null(bb)) bb <- 0
if(!is.null(cc)) cc <- 0
if(!is.null(dd)) dd <- 0
if(!is.null(ee)) ee <- 0
if(!is.null(ff)) ff <- 0
q <- list(aa, bb, cc, dd, ee, ff)
return(q)
}
testfunc(test)
This code works but it returns all NULL values. If I remove all of the NULL calls when I define the function, then I get the following error, "Error in testfunc(test) : object 'aa' not found"
testfunc <- function(x) {
unlist(x, recursive = TRUE, use.names = TRUE)
if(!is.null(aa)) aa <- 0
if(!is.null(bb)) bb <- 0
if(!is.null(cc)) cc <- 0
if(!is.null(dd)) dd <- 0
if(!is.null(ee)) ee <- 0
if(!is.null(ff)) ff <- 0
q <- list(aa, bb, cc, dd, ee, ff)
return(q)
}
testfunc(test)
Maybe it would help to define test as a dataframe instead of a list? Any help is appreciated!