Home > Blockchain >  How to reorder elements in a formula?
How to reorder elements in a formula?

Time:08-10

Suppose I have this formula: formula <- y~d|z|x. I want to reorder it to y~x|d|z. How do I do this?

I've tried:

as.Formula(formula(formula,lhs=1,rhs=3),formula(formula, lhs = 1, rhs = 1)[c(-2,-1)])

It obviously doesn't work.

CodePudding user response:

1) all.vars Extract the variables using all.vars, reorder them and then use reformulate to put them back together. This approach assumes that the components are single variables but the other alternatives allow general expressions as components.

fo <- y~d|z|x

v <- all.vars(fo)
reformulate(paste(v[c(4, 2, 3)], collapse = "|"), v[1], env = environment(fo))
## y ~ x | d | z

2) strings Convert to a string, split and reorder the components and then convert back to a formula. The last line is the same as in (1). The input fo was defined in (1).

s <- fo |>
  format() |>
  strsplit("[~|]") |>
  unlist()
reformulate(paste(s[c(4, 2, 3)], collapse = "|"), s[1], env = environment(fo))
## y ~ x | d | z

3) Formula Using the Formula package we can write the following. The input fo was defined in (1).

library(Formula)
formula(Formula(fo), lhs = 1, rhs = c(3, 1, 2))
## y ~ x | d | z

CodePudding user response:

formula <- y~d|z|x

a <- formula[[3]][[2]]
b <- formula[[3]][[3]]

formula[[3]][[2]][[2]] <- b
formula[[3]][[2]][[3]] <- a[[2]]
formula[[3]][[3]] <- a[[3]]

formula
#y ~ x | d | z

It's a bit difficult (but possible) to generalize because | is a function (and there are two nested calls) and you need to deal with the call tree.

  •  Tags:  
  • r
  • Related