How to get the length of a formula in R?

89 Views Asked by At

I am trying to get the length of the following formula:

myformula <- ~ (1 | Variable1) + (1|Sex) + Age + Cells + Glucose

But for some reason, R doesn't recognize the real number of elements (which is 5)

str(myformula)
Class 'formula'  language ~(1 | Variable1) + (1 | Sex) + Age + Neutrophils + Monocytes
  ..- attr(*, ".Environment")=<environment: R_GlobalEnv> 

length(myformula)
[1] 2

(Note: I have variables like this (1|Variable) because I am working with the Variance Partition package (and categorical variables must be written in that format).

Does anyone know how to get the real length of a formula in R?

1

There are 1 best solutions below

1
On BEST ANSWER

We may use all.vars to get the variables in the formula and then apply the length

length(all.vars(myformula))
[1] 5