From rich.fitzjohn at gmail.com  Thu Apr 21 01:52:12 2005
From: rich.fitzjohn at gmail.com (Rich FitzJohn)
Date: Thu Apr 21 01:52:21 2005
Subject: [Rd] Suggestions for manipulating formula objects
In-Reply-To: <33078.136.177.22.105.1114027536.squirrel@webmail.fpcc.net>
References: <33078.136.177.22.105.1114027536.squirrel@webmail.fpcc.net>
Message-ID: <5934ae570504201652af78001@mail.gmail.com>

Hi,

Formulas (and other language objects) can be manipulated to some
extent like lists (see the R Language Definition).  A formula
corresponds to a 3-element list, where the first argument is the
function `~`, and the next two are the LHS and RHS of the formula,
respectively (for unary use of ~, the list is 2 elements; `~` and the
single argument).

as.list(y ~ x)

The following function would apply the function "trans" to the
response of a formula "form".
addTransform <- function(form, trans) {
  stopifnot(inherits(form, "formula"),
            deparse(form[[1]]) == "~",
            is.function(match.fun(trans)))
  form[[2]] <- as.call(list(substitute(trans), form[[2]]))
  form
}

addTransform(y ~ x, sqrt)

## Testing this:
x <- 3*runif(20)
y <- sqrt(x*(2 + rnorm(20, sd=.1)))

f <- addTransform(y ~ x, sqrt)
lm(f) # Not a very informative call statement from lm()
lm(addTransform(y ~ x, sqrt)) # Slightly better call statement
do.call("lm", list(f)) # Matches appearence of the call below:
lm(sqrt(y) ~ x)

Cheers,
Rich


On 4/21/05, rlee@fpcc.net <rlee@fpcc.net> wrote:
> I'm trying to manipulate/change a formula prior to passing it to another
> function.  A simplified example:
> 
> User passes formula to my function: y~x
> My function does: lm(transform(y)~x)
> 
> Here, transform() is added to the model's response.
> 
> What is the best way to accomplish this?
> 
> ______________________________________________
> R-devel@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
> 


-- 
Rich FitzJohn
rich.fitzjohn <at> gmail.com   |    http://homepages.paradise.net.nz/richa183
                      You are in a maze of twisty little functions, all alike


[Rd] Suggestions for manipulating formula objects
Rich FitzJohn