[R] Character coerced to factor and I cannot get it back

Stephen Tucker brown_emu at yahoo.com
Fri Apr 20 05:57:15 CEST 2007


You can also set this option globally with options(stringsAsFactors = TRUE)

I believe this was added in R 2.4.0.



--- Gabor Grothendieck <ggrothendieck at gmail.com> wrote:

> Try this:
> 
> DF <- data.frame(let = letters[1:3], num = 1:3, stringsAsFactors = FALSE)
> str(DF)
> 
> 
> On 4/19/07, John Kane <jrkrideau at yahoo.ca> wrote:
> >
> > --- Tyler Smith <tyler.smith at mail.mcgill.ca> wrote:
> >
> > > I really need to sit down with the manual and sort
> > > factors and classes
> > > properly. In your case, I think the problem has
> > > something to do with
> > > the way a list behaves?  I'm not sure, but if you
> > > convert your list to
> > > a dataframe it seems to work ok:
> > >
> > > > dd3 <- as.data.frame(dd1)
> > > > typeof(dd3$st)
> > > [1] "integer"
> > > > class(dd3$st)
> > > [1] "factor"
> > > > dd3$st <- as.character(dd3$st)
> > > > typeof(dd3$st)
> > > [1] "character"
> > > > class(dd3$st)
> > > [1] "character"
> > >
> > > HTH,
> > >
> > > Tyler
> >
> > Seems to work nicely. I had forgotten about
> > 'as.data.frame.
> >
> > I originally thought that it might be a list problem
> > too but I don't think so. I set up the example as a
> > list since that is the way my real data is being
> > imported from csv. However after my original posting I
> > went back and tried it with just a dataframe and I'm
> > getting the same results. See below.
> >
> > I even shut down R , reloaded it and detached the two
> > extra packages I usually load. Everything is working
> > fine but I am doing some things with factors that I
> > have never done before and this just makes me a bit
> > paranoid.
> >
> > Thanks very much for the help.
> >
> >
> > EXAMPLE
> > dd  <- data.frame(aa <- 1:4, bb <-  letters[1:4],
> >         cc <- c(12345, 123456, 45678, 456789))
> >
> > id  <-  as.character(dd[,3]) ; id
> >
> > st  <- substring(id, 1,nchar(id)-4 ) ; st
> > typeof (st)  ; class(st)
> >
> > dd1  <-  cbind(dd, st)
> >    names(dd1)  <- c("aa","bb","cc","st")
> >    dd1
> >    typeof(dd1$st); class(dd1$st)
> >
> > dd2  <-  cbind(dd, as.character(st))
> >    names(dd2)  <- c("aa","bb","cc","st")
> >    dd2
> >    typeof(dd2$st) ;   class(dd2$st)
> >
> > ______________________________________________
> > 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
> > and provide commented, minimal, self-contained, reproducible code.
> >
> 
> ______________________________________________
> 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
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list