[R] How to construct a formula

Duncan Murdoch murdoch.duncan at gmail.com
Sun Jan 22 16:38:47 CET 2012


On 12-01-22 9:27 AM, Hugh Morgan wrote:
> Hi,
>
> I need to construct a formula programaticly, and pass it to a function
> such as the linear mixed model lme.  The help says it requires "a
> two-sided linear formula object describing the fixed-effects part of the
> model" but I do not know how to create this formula.  I have tried
> various things using formula(x, ...), as.formula(object, env =
> parent.frame()) and as.Formula(x, ...) but I cannot get it to work.  Can
> anyone give me any pointers?
>
> What I want to do is pass particular columns to my mixed model depending
> on the result of a previous test (anova) in a programatic way.  I could
> use hard coded if statements as in the example below, but I want to be
> able to do this in a more programatic way.  I hope the code below will
> show what I am trying to do:
>
> Current code:
>
> data=read.csv("dataMini.csv", header=TRUE, sep=",", dec=".")
> colnames(data)
> library(nlme)
>
> if(weight_significant) {
>       if(gender_significant) {
>           if(weight_gender_interaction_significant) {
>               model=lme(test_variable~Genotype + Weight + Gender +
> Weight*Gender, random=~1|Assay.Date, data, na.action="na.exclude",
> method="REML")
>           } else {
>               model=lme(test_variable~Genotype + Weight + Gender,
> random=~1|Assay.Date, data, na.action="na.exclude", method="REML")
>           }
>       } else {
> .... etc
>
> What I want to do:
>
> formulaObject = test_variable~Genotype
> if(weight_significant) {
>       formulaObject = formulaObject + Weight;
> }
> if(gender_significant) {
>       formulaObject = formulaObject +  Gender;
> }
> if(weight_gender_interaction_significant) {
>       formulaObject = formulaObject +  Weight*Gender;
> }

I think you don't really want that; you want to add those terms to the 
right hand side of the formula.

This function would do that:

addterm <- function(fla, term) {
   fla[[3]] <- call("+", fla[[3]], substitute(term))
   fla
}

For example,

 > formulaObject
test_variable ~ Genotype
 > addterm(formulaObject, Weight)
test_variable ~ Genotype + Weight

Duncan Murdoch


> model=lme(formulaObject, random=~1|Assay.Date, data,
> na.action="na.exclude", method="REML")



More information about the R-help mailing list