reformulate
将实现你想要的功能。
reformulate(termlabels = c('x','z'), response = 'y')
或者去掉截距
reformulate(termlabels = c('x','z'), response = 'y', intercept = FALSE)
请注意,您不能构建包含多个
reponses
的公式,例如
x+y ~z+b
。
reformulate(termlabels = c('x','y'), response = c('z','b'))
z ~ x + y
从一个现有的公式中提取术语(根据您的示例给出)
attr(terms(RHS), 'term.labels')
要获得响应有些不同,一个简单的方法(用于单个变量响应)。
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
你也可以谨慎地使用 update.formula
,使用 .
符号。
update(~a+b, y ~ .)
## y~a+b