[R] Modifying a function programmatically

Søren Højsgaard sorenh at math.aau.dk
Mon Feb 4 11:00:50 CET 2013


Dear list

# I have a function 
 ff  <- function(a,b=2,c=4){a+b+c}
# which I programmatically want to modify to a more specialized function in which a is replaced by 1
 ff1 <- function(b=2,c=4){1+b+c}

# I do as follows:
 vals  <- list(a=1)
 (expr1 <- as.expression(body(ff)))
expression({
    a + b + c
})
 (expr2 <- do.call("substitute", list(expr1[[1]], vals)))
{
    1 + b + c
}
 
 # This "works", 
 eval(expr2, list(b=10,c=12))
[1] 23
 
 # - but I would like a function. Hence I do:
 ll  <- alist(b=, c=, eval(expr2))
 ff2 <- as.function(ll)
 ff2(b=10,c=12)
[1] 23
 
 # BUT I am only half-way where I want to be because the alist(b=, c=, ...) 
 # requires me plugin the remaining formals by hand. I do:
 newformals <-setdiff(names(formals(ff)), names(vals))
 vv         <- vector("list", length(newformals))
 names(vv)  <- newformals
 (hh <- c(vv, expr2))
$b
NULL
$c
NULL
[[3]]
{
    1 + b + c
}

 (ff3 <- as.function(hh))
function (b = NULL, c = NULL) 
{
    1 + b + c
}
 ff3(10,12)
[1] 23
 # Hence I get the function that returns what I want (given the correct input) 
 # but the arguments will have default values that I don't want. 
 # I want to retain the original default values (if any)
 ff1()
[1] 7
 ff3()
numeric(0)

I have two questions: 
1) How to fix the above?
2) Aren't there more elegant alternatives?

Any help would be appreciated.
Regards
Søren
 



More information about the R-help mailing list