Question

I'm trying to write a wrapper for a function in order to use lists as input. I cannot change the function itself, therefore I need a workaround outside of it. I use as.call() and it works without optional arguments, but I fail to make it work when I have vectors as optional arguments.

Example:

# function I cannot change
func <- function(..., opt=c(1,2)) {
    cl <- match.call(expand.dots = FALSE)
    names <- lapply(cl[[2]],as.character)  
    ev <- parent.frame()
    classes <- unlist(lapply(names,function(name){class(get(name,envir=ev))}))    
    print(c(opt,names, classes))
}

a <- structure(1:3, class="My_Class")
b <- structure(letters[1:3], class="My_Class")

lst <- list(a, b)
names(lst) <- c("a","b")

# Normal result
func(a,b,opt=c(3,4))

# This should give the same but it doesn't
call <- as.call(append(list(func), list(names(lst), opt=c(3,4))))
g <- eval(call, lst)

Instead of a list as optional argument, I also tried c(), but this doesn't work either. Does anybody have a suggestion or a help page? ?call wasn't to clear about my problem.

(I already asked a previous question to the topic here: R: How to use list elements like arguments in ellipsis? , but left out the detail about the optional parameter and cannot figure it out now.)

Was it helpful?

Solution

This produces the same result for me under both versions

call <- as.call(c(list(quote(func)), lapply(names(lst), as.name), list(opt=c(3,4))))
g <- eval(call, lst)

EDIT: as per Hadley's suggestions in comments.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top