Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap RHS terms of a formula with a function

Tags:

r

formula

I can construct a formula that does what I desire starting with the character versions of terms in a formula, but I'm stumbling in starting with a formula object:

form1 <- Y ~ A + B 
form1[-c(1,2)][[1]]
#A + B

Now how to build a formula object that looks like:

 Y ~ poly(A, 2) + poly(B, 2) + poly(C, 2)

Or:

 Y ~ pspline(A, 4) + pspline(B, 4) + pspline(C, 4)

Seems that it might involve a recursive walk along the RHS but I'm not getting progress. It just occurred to me that I might use

> attr( terms(form1), "term.labels")
[1] "A" "B"

And then use the as.formula(character-expr) approach, but I's sorly of like to see an lapply (RHS_form, somefunc) version of a polyize (or perhaps polymer?) function.

like image 390
IRTFM Avatar asked Mar 06 '16 16:03

IRTFM


2 Answers

If I borrow some functions I originally wrote here, you could do something like this. First, the helper functions...

extract_rhs_symbols <- function(x) {
    as.list(attr(delete.response(terms(x)), "variables"))[-1]
}
symbols_to_formula <- function(x) {
    as.call(list(quote(`~`), x))    
}
sum_symbols <- function(...) {
    Reduce(function(a,b) bquote(.(a)+.(b)), do.call(`c`, list(...), quote=T))
}
transform_terms <- function(x, f) {
    symbols_to_formula(sum_symbols(sapply(extract_rhs_symbols(x), function(x) do.call("substitute",list(f, list(x=x))))))
}

And then you can use

update(form1, transform_terms(form1, quote(poly(x, 2))))
# Y ~ poly(A, 2) + poly(B, 2)

update(form1, transform_terms(form1, quote(pspline(x, 4))))
# Y ~ pspline(A, 4) + pspline(B, 4)
like image 134
MrFlick Avatar answered Nov 13 '22 08:11

MrFlick


There's a formula.tools package that provides various utility functions for working with formulas.

f <- y ~ a + b
rhs(f)                        # a + b
x <- get.vars(rhs(f))         # "a" "b"
r <- paste(sprintf("poly(%s, 4)", x), collapse=" + ")  # "poly(a, 4) + poly(b, 4)"
rhs(f) <- parse(text=r)[[1]]
f                             # y ~ poly(a, 4) + poly(b, 4)
like image 38
Hong Ooi Avatar answered Nov 13 '22 06:11

Hong Ooi