s-news
[Top] [All Lists]

Re: Writing a function taking a data.frame column name as a parameter

To: <s-news@lists.biostat.wustl.edu>
Subject: Re: Writing a function taking a data.frame column name as a parameter
From: "Hunsicker, Lawrence" <lawrence-hunsicker@uiowa.edu>
Date: Sat, 27 Dec 2008 18:43:45 -0600
Thread-index: AclohVcbLhsKnZA1SEKt1bX9WQuh8g==
Thread-topic: 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 dont have the scope stuff understood properly.  I cant get the sapply function to do what I am trying to do.

Larry Hunsicker

<Prev in Thread] Current Thread [Next in Thread>