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

John Kane jrkrideau at yahoo.ca
Thu Apr 19 21:40:08 CEST 2007


--- 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)



More information about the R-help mailing list