Skip to content
Prev 7489 / 12125 Next

[R-pkg-devel] update.formula does not keep.order

On 27/10/2021 7:16 p.m., Chris Brien wrote:
I can't think of a short term solution.  The long term solution is to 
prepare and submit a patch to R to add the keep_order argument to 
update.formula.

As a workaround, perhaps you could modify the result of update() to 
restore the original order.  This sounds messy, but if you already have 
code to manipulate formulae, maybe it's mostly in place.  The steps 
would be:

  Decompose the formula into a vector of terms, e.g. ~A + B + A:B + C + 
D + C:D becomes

old <- expression(A, B, A:B, C, D, C:D)

  Update the formula, and decompose the new formula in the same way.

So A + B + D + A:B + C:D becomes

new <- expression(A, B, D, A:B, C:D)


  Match each term in the new vector to its location in the original 
vector, and sort it.

index <- match(new, old)
sorted <- order(index)
new[sorted]

In your example, this gives expression(A, B, A:B, D, C:D) .


  (You'll need to decide what to do with terms that weren't present in 
the original.  They'll have NA values in index.  Presumably they go to 
the end.)

  Rebuild the formula after sorting.

Duncan Murdoch