[R] How to construct a formula
Hugh Morgan
h.morgan at har.mrc.ac.uk
Sun Jan 22 15:27:17 CET 2012
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;
}
model=lme(formulaObject, random=~1|Assay.Date, data,
na.action="na.exclude", method="REML")
This email may have a PROTECTIVE MARKING, for an explanation please see:
http://www.mrc.ac.uk/About/Informationandstandards/Documentmarking/index.htm
More information about the R-help
mailing list