在R中更新公式

15

我有一个公式对象form1

 form1 = y ~ 1 + x*y

我想在这个公式中添加一个新的项,比如+z,使得我的form2变成下面这样:

 form2 = y ~ 1 + x*y + z.

我发现了一种非常繁琐的方法来做到这一点:

terms.form1 <- terms(form1)
terms.labels <- attr(terms.form1,"term.labels")
old.terms <- paste(terms.labels,collapse=" + ")
updated.terms <- paste(old.terms," + z",collapse=" + ")

form2 = as.formula(paste(as.character(form1[[2]]),"~",updated.terms,collapse=""))
尽管这样可以得到form2,但我想知道是否有更简单的方法来做到这一点。
提前感谢你!
1个回答

26
你应该使用 update.formula
update(y ~ 1 + x*y,    ~ . + z)
y ~ x + y + z + y:x

.表示"公式中此处之前的内容"


我看到过.~.符号。但不知道它的含义是什么?你能给我这些符号的参考资料吗? - ABC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接