Martin Spindler
2011-Feb-08 04:33 UTC
[R] partial evaluation of a function with several arguments
Dear all, I have the following problem: add <- function(x,y) {x+y} What is the easiest / most elegant way to create a new function (e.g. with the name "addev") that sets the second argument of the function "add" to a fixed value (e.g. y=3), i.e. addev <- add(x,3). But this does not work. Thank you for your efforts in advance! Best, Martin -- -- Empfehlen Sie GMX DSL Ihren Freunden und Bekannten und wir belohnen Sie mit bis zu 50,- Euro! https://freundschaftswerbung.gmx.de
David Winsemius
2011-Feb-08 05:06 UTC
[R] partial evaluation of a function with several arguments
On Feb 7, 2011, at 11:33 PM, Martin Spindler wrote:> Dear all, > > I have the following problem: > > add <- function(x,y) {x+y} > > What is the easiest / most elegant way to create a new function > (e.g. with the name "addev") that sets the second argument of the > function "add" to a fixed value (e.g. y=3), i.e. addev <- add(x,3). > But this does not work.> add <- function(x,y) {x+y} > addev <- add > formals(addev) <- alist(x=,y=3) > addev(1) [1] 4 Although that might not be what you meant by "fixed" so this is another method with a different result: > addev <- add > body(addev) <- quote(x+3) > addev(4) [1] 7> > Thank you for your efforts in advance! > > Best, > > Martin > -- > > > > > -- > Empfehlen Sie GMX DSL Ihren Freunden und Bekannten und wir > belohnen Sie mit bis zu 50,- Euro! https://freundschaftswerbung.gmx.de > > ______________________________________________ > 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.David Winsemius, MD West Hartford, CT
Gabor Grothendieck
2011-Feb-08 13:15 UTC
[R] partial evaluation of a function with several arguments
On Mon, Feb 7, 2011 at 11:33 PM, Martin Spindler <Martin.Spindler at gmx.de> wrote:> Dear all, > > I have the following problem: > > add <- function(x,y) {x+y} > > What is the easiest / most elegant way to create a new function (e.g. with the name "addev") that sets the second argument of the function "add" to a fixed value (e.g. y=3), i.e. addev <- add(x,3). But this does not work. > > Thank you for your efforts in advance! >The Defaults package can do that:> library(Defaults) > > add <- function(x,y) {x+y} > setDefaults(add, y=3) > > add(1)[1] 4 We can look at what has happened to add. Functions have a source attribute that show the source text of the function but that text is not changed by setDefaults so we need to remove it to be sure we are looking at the actual function and not the source text:> attr(add, "source") <- NULL > addfunction (x, y) { if (exists(".importDefaults")) .importDefaults(calling.fun = "add") x + y }>-- Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com