I would like to count the number of variables that enter into the right hand side of a formula. Is there a function that does this?
For example:
y<-rnorm(100)
x1<-rnorm(100)
x2<-rnorm(100)
x3<-rnorm(100)
f<-formula(y~x1+x2+x3)
Then, I would call SomeFunction(f) which would return 3 (since there are 3 x variables on the right hand side of the equation). Does SomeFunction exist?
You might need to look at some of the related functions linked in the help page for formula. In particular, terms:
> terms(f)
y ~ x1 + x2 + x3 + x4
attr(,"variables")
list(y, x1, x2, x3, x4)
attr(,"factors")
x1 x2 x3 x4
y 0 0 0 0
x1 1 0 0 0
x2 0 1 0 0
x3 0 0 1 0
x4 0 0 0 1
attr(,"term.labels")
[1] "x1" "x2" "x3" "x4"
attr(,"order")
[1] 1 1 1 1
attr(,"intercept")
[1] 1
attr(,"response")
[1] 1
attr(,".Environment")
<environment: R_GlobalEnv>
Note the "term.labels" attribute.
Here are two possibilities:
length(attr(terms(f), "term.labels"))
length(all.vars(update(f, z ~.))) - 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With