Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting variables in a formula

Tags:

r

formula

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?

like image 273
BUML1290 Avatar asked Aug 16 '13 19:08

BUML1290


Video Answer


2 Answers

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.

like image 94
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 28 '22 07:09

A5C1D2H2I1M1N2O1R2T1


Here are two possibilities:

length(attr(terms(f), "term.labels"))

length(all.vars(update(f, z ~.))) - 1
like image 33
G. Grothendieck Avatar answered Sep 28 '22 08:09

G. Grothendieck