Probably a lot easier just to do:
# Fuel example
lm.function<-function(x){
fuel.frame<-select.cols(fuel.frame,x)
return(summary(lm(Fuel ~ . , data="">
# Model Fuel with Weight and Disp
lm.function(c("Weight","Disp","Fuel"))
# Model Fuel with Weight only
lm.function(c("Weight","Fuel"))
Steve
-----Original Message-----
From: s-news-owner@lists.biostat.wustl.edu on behalf of Hunsicker, Lawrence
Sent: Sun 28/12/2008 11:43
To: s-news@lists.biostat.wustl.edu
Subject: Re: [S] Writing a function taking a data.frame column name as a parameter
Thanks, all of those that responded above. I learned a lot from this
exercise - about [[x]] to get the contents of a list rather than the
list itself (which I knew but had forgotten), about "as.formula" which
is the magic that turns a pasted piece of text into something that looks
to S-plus like a formula, and finally, that a parameter name has to be
standing alone to have the passed value substituted into it. My basic
problem is that I was trying to get the passed parameter substituted for
the x in something like "my.data.frame$x."
While there are probably several of the suggestions that I could
probably have gotten to work, I return the following two:
From Alan Hockberg:
testanyCVD1 <- function(x) {
temp <- working7[!is.na(working7[[x]]),]
any.glmm<-glmmPQL(fixed = as.formula(paste("anyCVD ~
",names(temp)[x],sep=''))
, random = ~1|Region/Pays/Center, family =
binomial(link=logit),data="" = F, niter=15)
list(names(temp)[x], anova(any.glmm), any.glmm$coefficients$fixed)
}
Here it was the delisting operator in line 2, and the "as.formula"
function in line 3 that got the function working.
From Andreas Kraus, maybe not quite as elegant but really simple and
convenient:
testanyCVD <- function(x) {
temp <- working7[!is.na(working7[[x]]),]
temp$x <- temp[[x]]
any.glmm<-glmmPQL(fixed = anyCVD ~ x
, random = ~1|Region/Pays/Center, family =
binomial(link=logit),data="" = F, niter=15)
list(names(temp)[x], anova(any.glmm), any.glmm$coefficients$fixed)
}
He suggested creating a new column in "temp" named x, as in line 3
above, again using the delisting operator. Now the function works right
because temp$x exists, and in fact is identical to the column originally
indexed by x.
Thanks to all of you. This got me a function that works correctly. But
as you will note in my next message, I still don't have the scope stuff
understood properly. I can't get the sapply function to do what I am
trying to do.
Larry Hunsicker
|