Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

r - expanding factor interactions within a formula

I have many formulas (of class formula or Formula) of the form y ~ a*b, where a and b are factors.

I need to write a function that takes such a formula and returns a formula with all of the terms in the interaction "spelled out." Here is an example:

fac1 <- factor(c('a', 'a', 'b', 'b'))
fac2 <- factor(c('c', 'd', 'c', 'd'))
BigFormula(formula(x ~ fac1*fac2))

where BigFormula returns formula(x ~ a + b + c + d + a:c + a:d + b:c + b:d).

Is there a simple way to do this?

(The context: I am running many commands of the form anova(mod1, mod2), where mod2 nests in mod1, and where the right-hand side of both models contains terms like fac1*fac2. The point of these commands is to calculate F-statistics. The problem is that anova treats fac1*fac2 as three variables, even though it usually represents more than three variables. (In the code above, for example, fac1*fac2 represents eight variables.) As a result, anova underestimates the number of restrictions in the nested model, and it overestimates my degrees of freedom.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Look at the help for formula there may be existing things that will work for you.

For example the formula y ~ (a + b + c + d)^2 will give you all main effects and all 2 way interactions and the formula y ~ (a + b) * (c + d) gives the expansion that you show above. You can also subtract terms so y ~ a*b*c - a:b:c will not include the 3 way interaction.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...