如何用函数包装公式的 RHS 项
How to wrap RHS terms of a formula with a function
我可以构建一个公式来执行我想要的操作,从公式中术语的字符版本开始,但我在从公式对象开始时遇到困难:
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
?)功能。
如果我借用我原来写的一些功能,你可以做这样的事情。首先,辅助函数...
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)
有一个 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)
我可以构建一个公式来执行我想要的操作,从公式中术语的字符版本开始,但我在从公式对象开始时遇到困难:
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
?)功能。
如果我借用我原来写的一些功能
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)
有一个 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)