2

I would like to dynamically update a formula with a vector under R 4.0.0 or higher. Hence everything is the same as under this link - R: Dynamically update formula - but x is now a vector, and the R version is >= 4.0. In short, I have a formula, e.g. y ~ 1, and would like to update it via the character scalar myvar1 or the character vector myvar2. For character vectors and R versions >= 4.0.0, the suggested solution fails for character vectors. In the release note for 4.0.0, this is mentioned as a bug fix. The note states that "formula(x) with length(x) > 1 character vectors, is deprecated now. Such use has been rare, and has ‘worked’ as expected in some cases only. In other cases, wrong x have silently been truncated, not detecting previous errors." (https://cran.r-project.org/doc/manuals/r-patched/NEWS.html)

myvar1 <- "x1"
myvar2 <- c("x1", "x2")
update(y ~ 1 , paste(" ~ . +", myvar1))
# y ~ x1
update(y ~ 1 , paste(" ~ . +", myvar2))
# y ~ x1
# Warning message:
# Using formula(x) is deprecated when x is a character vector of length > 1.
  Consider formula(paste(x, collapse = " ")) instead. 

So, how would I update a formula with a character vector in R 4.0.0 and higher?

A.Fischer
  • 596
  • 5
  • 11

2 Answers2

2

What you need to do now is to manipulate your string so that you obtain: "~ . + x1 + x2".

myvar2 <- c("x1", "x2")

formula_update <- paste(
  "~ . +",
  paste(myvar2, collapse = " + ")
)

formula_update 
[1] "~ . + x1 + x2"

update(y ~ 1, formula_update)
y ~ x1 + x2
SavedByJESUS
  • 3,262
  • 4
  • 32
  • 47
2

Would you consider

reformulate(myvar1, response="y")

an acceptable substitute? (It doesn't do exactly the same thing but might work.)

You could also make your update-argument a formula ...

update(y~1, reformulate(c(".",myvar1)))
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453