Philip Whittall | 1 Dec 13:09
Favicon

Coercing a list of variables in a function call

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)

Favicon

Re: Coercing a list of variables in a function call

try the following:

model.it <- function (form, data, factor.id) {
     if (!missing(factor.id) && all(factor.id %in% names(data)))
         data[factor.id] <- lapply(data[factor.id], factor)
     glm(form, data = data)
}

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 <- data.frame(y, x1, x2, x3)

model.it(y ~ x1 + x2 + x3, d, c("x1", "x2"))
model.it(y ~ x1 + x2 + x3, d)

If you only plan to fit linear regression models, then it is advisable 
that you lm() instead of glm(). I hope it helps.

Best,
Dimitris

Philip Whittall wrote:
> 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, 
(Continue reading)


Gmane