I would like to define different parts of a formula in R and then concatenate these parts - not necessarily only by adding the terms up. I could imagine a syntax like this:
# define one-handed formulas
part_1 <- ~ x:w
part_2 <- ~ y + z
# concatenate, e.g. with glue syntax
f <- y ~ a + {part_1}:{part_2}
To me, this appears to be a natural application, so I am wondering if there is this sort of functionality in base R. Some packages do offer solutions but come with other strings attached.
My efforts to do this in base R did not succeed:
# does not work: update inserts "part_2" literally
update(part_1, ~ . + part_2)
#> ~part_2 + x:w
# reformulate uses + to concatenate
reformulate(c(attr(terms(part_1), "term.labels"),
attr(terms(part_2), "term.labels")))
#> ~x:w + y + z
Merge methods for formulas have been written (e.g., here and here) but do not allow concatenating with anything other than addition.
The only solution that I could find so far involves the macro notation from fixest
:
library(fixest)
setFixest_fml(..part_1 = ~ x:w)
setFixest_fml(..part_2 = ~ y + z)
f <- y ~ a + (..part_1):(..part_2)
xpd(f)
#> y ~ a + (x:w):(y + z)
attr(terms(xpd(f)), "term.labels")
#> [1] "a" "y:x:w" "x:w:z"
Created on 2021-11-18 by the reprex package (v2.0.1)