[R] Modifying a function programmatically

Pascal Oettli kridox at ymail.com
Mon Feb 4 11:10:44 CET 2013


Hi,

Is it what you are looking for?

 > ff  <- function(a,b,c){a+b+c}

 > ff(1,10,12)
[1] 23

 > ff(589,2,4)
[1] 595

HTH,
Pascal


Le 04/02/2013 19:00, Søren Højsgaard a écrit :
> 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
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list