I want to add extra variables to a formula, with the use of a separate object part_B
. As an example:
part_A <- as.formula("y ~ x1")
part_B <- c("x2", "x3")
I tried a couple of things, but one issue is that you cannot call as.formula
on the object part_B
(because in that case I could have created the formula by combining character vectors).
Desired Result
as.formula("y ~ x1 + x2 + x3")
Is there any way to do this? I guess one solution would be to create a function that writes the character vector as "y ~ x1 + x2 + x3"
so it can be fed to as.formula
.
Use reformulate and update like this:
update(part_A, reformulate(c(".", part_B)))
## y ~ x1 + x2 + x3
This also works:
v <- all.vars(part_A)
reformulate(c(v[-1], part_B), v[1])
## y ~ x1 + x2 + x3