1 Dec 13:09
Coercing a list of variables in a function call
From: Philip Whittall <Philip.whittall <at> detica.com>
Subject: Coercing a list of variables in a function call
Newsgroups: gmane.comp.lang.r.general
Date: 2008-12-01 12:09:41 GMT
Subject: Coercing a list of variables in a function call
Newsgroups: gmane.comp.lang.r.general
Date: 2008-12-01 12:09:41 GMT
This is hopefully a trivial problem for list subscribers, but I am very
new to writing R functions.
I wish to call an R function written by myself from another program to
fit a model. I need
to tell it which of the independent variables are factors. I need to do
this in a generic way,
so that when the list is passed, R will work through the variables in
the data frame and coerce them into being factors.
This is what I tried ...
# Fictitious data for illustration
y<-c(1,2.1,3.3,4.3,5,6.5)
x1<-c(1,1,1,2,2,2)
x2<-c(1,2,3,1,2,3)
x3<-c(1,3,2,4,2,4)
d<-as.data.frame(cbind(y,x1,x2,x3))
#Function definition
model_it=function(data=" ", model=" ", factors=list()){
attach(d) #Attach the data
formula<-as.formula(model) #Set up the model
#Identify the factors
if (length(factors)>0) for(i in 1:length(factors)){
factors[i]<-as.factor(factors[i])
}
#Fit the model
glm(formula, data=data)
}
#Function call attempted
model_it(data=d, model="y~x1+x2+x3", factors=list(x1,x2))
(Continue reading)
RSS Feed