[R] cannot turn some columns in a data frame into factors

Douglas Grove dgrove at fhcrc.org
Thu May 11 18:41:07 CEST 2006


You need to create a new object and assign it to 'df'

so you'd do something like this:

df <- sapply(factors, function (name) {
             pos <- match(name,df.names)
             factor(df[[pos]])
             })
             

Doug






On Thu, 11 May 2006, Sam Steingold wrote:

> > * jim holtman <wubygzna at tznvy.pbz> [2006-05-11 12:27:39 -0400]:
> >
> > try '<<-' as the assignment to make it global.
> >
> >      df[[pos]] <<- factor(df[[pos]])
> 
> nothing changed -- I observe the exact same behaviour:
> 
> Month ( 1 ): TRUE 
> factors: FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 
> 
> 
> > On 5/11/06, Sam Steingold <sds at podval.org> wrote:
> >>
> >> Hi,
> >> I have a data frame df and a list of names of columns that I want to
> >> turn into factors:
> >>
> >> df.names <- attr(df,"names")
> >> sapply(factors, function (name) {
> >>    pos <- match(name,df.names)
> >>    if (is.na(pos)) stop(paste(name,": no such column\n"))
> >>    df[[pos]] <- factor(df[[pos]])
> >>    cat(name,"(",pos,"):",is.factor(df[[pos]]),"\n")
> >> })
> >> cat("factors:",sapply(df,is.factor),"\n")
> >>
> >> the output is:
> >>
> >>
> >> Month ( 1 ): TRUE
> >> factors: FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> >>
> >>
> >> i.e., there is a column named "Month" (the 1st column), and it is indeed
> >> turned into a factor inside sapply(), but after that it is numerical
> >> again!
> >>
> >> what am I doing wrong?
> 
> -- 
> Sam Steingold (http://www.podval.org/~sds) on Fedora Core release 5 (Bordeaux)
> http://pmw.org.il http://ffii.org http://memri.org http://palestinefacts.org
> http://truepeace.org http://mideasttruth.com http://dhimmi.com
> If you're being passed on the right, you're in the wrong lane.
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list