How to Wrap RHS Formula Conditions Using a Function

I can build a formula that does what I want, starting with the symbolic versions of the terms in the formula, but I stumble starting from the formula object:

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

Now, how to build a formula object that looks like this:

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

Or:

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

It seems like it could be a recursive walk on RHS, but I am not getting progress. It just occurred to me that I can use

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

And then use the approach as.formula(character-expr), but I really like to see the version of the lapply (RHS_form, somefunc)function polyize(or maybe polymer?).

+4
source share
2 answers

, , - . -, ...

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))))))
}

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)
+4

formula.tools , .

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)
+4

All Articles