如何用函数包装公式的RHS项

时间:2016-03-06 16:39:27

标签: r formula

我可以构建一个公式,从公式中的术语的字符版本开始做我想要的,但是我在使用公式对象时遇到了绊脚石:

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

现在如何构建一个看起来像的公式对象:

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

或者:

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

似乎可能涉及沿着RHS的递归步行,但我没有取得进展。我突然意识到我可能会使用

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

然后使用as.formula(character-expr)方法,但我很想看到lapply (RHS_form, somefunc)版本polyize(或者polymer?)功能

2 个答案:

答案 0 :(得分:4)

如果我借用一些我最初编写here的函数,你可以做这样的事情。首先,辅助函数......

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)

答案 1 :(得分: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)