[Rd] Suggestions for manipulating formula objects
Rich FitzJohn
rich.fitzjohn at gmail.com
Thu Apr 21 01:52:12 CEST 2005
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 at fpcc.net <rlee at 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 at 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
More information about the R-devel
mailing list