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
使用.
明智
update(~a+b, y ~ .)
## y~a+b
即使我最終意識到我不需要相當的普遍性水平,而是更好地使用'update'函數,mnel的答案是一個很好的和有用的答案,並且可能已經完成了我原本是在嘗試。但總的來說,我贊成很好的答案,但不接受他們,直到我真正嘗試並能爲他們擔保。在很多情況下,我自己找到了更好的答案,並且當我有時間時應該提交自我回答。我接受答案的標準太嚴格了嗎? – f1r3br4nd