有没有更好的select比string操作以编程方式build立公式?

其他人的function似乎都采取了公式化的对象,然后在内心深处做出黑魔法,我很嫉妒。

我正在写一个适合多个模型的函数。 这些模型的部分公式保持不变,并且从一个模型到另一个模型的部分变化。 笨拙的方法是让用户input公式部分作为string,对它们进行一些字符操作,然后使用as.formula

但是在我走这条路线之前,我只想确保我不会忽略一些更简洁的方法,让函数接受标准R格式的公式(例如从其他使用公式的对象中提取)。

我想要像…

 > LHS <- y~1; RHS <- ~a+b; c(LHS,RHS); y ~ a + b > RHS2 <- ~c; > c(LHS, RHS, RHS2); y ~ a + b + c 

要么…

 > LHS + RHS; y ~ a + b > LHS + RHS + RHS2; y ~ a + b + c 

…但不幸的是没有语法的作品。 有人知道是否有这样的事情吗? 谢谢。

reformulate会做你想要的。

 reformulate(termlabels = c('x','z'), response = 'y') ## y ~ x + z 

或者没有拦截

 reformulate(termlabels = c('x','z'), response = 'y', intercept = FALSE) ## y ~ x + z - 1 

请注意,您不能构build具有多个reponses公式,例如x+y ~z+b 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" 

为了得到答案略有不同,一个简单的方法(对于一个单一的variables响应)。

 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