reformulate
会做你想做的。
reformulate(termlabels = c('x','z'), response = 'y')
## y ~ x + z
或者没有拦截
reformulate(termlabels = c('x','z'), response = 'y', intercept = FALSE)
## y ~ x + z - 1
请注意,您不能构造具有多个公式的公式,reponses
例如x+y ~z+b
reformulate(termlabels = c('x','y'), response = c('z','b'))
z ~ x + y
从现有的formula
(给定您的示例)中提取术语
attr(terms(RHS), 'term.labels')
## [1] "a" "b"
得到的响应稍有不同,一种简单的方法(对于单变量响应)。
as.character(LHS)[2]
## [1] 'y'
combine_formula <- function(LHS, RHS){
.terms <- lapply(RHS, terms)
new_terms <- unique(unlist(lapply(.terms, attr, which = 'term.labels')))
response <- as.character(LHS)[2]
reformulate(new_terms, response)
}
combine_formula(LHS, list(RHS, RHS2))
## y ~ a + b + c
## <environment: 0x577fb908>
我认为将响应指定为字符向量会更明智,例如
combine_formula2 <- function(response, RHS, intercept = TRUE){
.terms <- lapply(RHS, terms)
new_terms <- unique(unlist(lapply(.terms, attr, which = 'term.labels')))
response <- as.character(LHS)[2]
reformulate(new_terms, response, intercept)
}
combine_formula2('y', list(RHS, RHS2))
您还可以定义一个+
运算符来处理公式(更新为公式对象设置新方法)
`+.formula` <- function(e1,e2){
.terms <- lapply(c(e1,e2), terms)
reformulate(unique(unlist(lapply(.terms, attr, which = 'term.labels'))))
}
RHS + RHS2
## ~a + b + c
您也可以明智地使用update.formula
using.
update(~a+b, y ~ .)
## y~a+b