[R] Help with declaring factors in a function

William Dunlap wdunlap at tibco.com
Thu Feb 19 03:24:04 CET 2015


You did not put the altered columns back into the data.frame,
so glm() never saw them.  Does the following work?

func <- function(x,y,z) {
#x is a data frame
#y is a formula for the regression
#z vector of names of columns of x to convert to factors
    for (name in z) {
        x[[name]] <- factor(x[[name]])
    }
    glm(y, x, family=binomial(link = "logit"))
}


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Wed, Feb 18, 2015 at 5:40 PM, Evan Kransdorf <evan.kransdorf at gmail.com>
wrote:

> Hello,
>
> I am passing a df to a function and then want to declare factors (based on
> a vector of column names in the df) for a logistic regression. I am having
> trouble - R doesn't seem to recognize the factors as declared in the
> function? Below is my code.  Does anyone have any ideas?
>
> MyFunction <- function(x,y,z) {
> #x is a data frame
> #y is a formula for the regression
> #z vector of factors to be declared
>     name<-NULL
>     temp<-NULL
>     for (i in 1 : length(z)) {
>         name<-paste0(substitute(x),"$",z[i])
>         print(name)
>         temp<-eval(parse(text = name))
>         temp<-factor(temp)
>         print(levels(temp))
>     } #for
>     model<-glm(y, x, family=binomial(link = "logit"))
>     return(model)
> } #func
>
> Thanks very much!!!
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list