[R] factors to integers preserving value in a dataframe

David Winsemius dwinsemius at comcast.net
Fri Feb 27 21:15:28 CET 2009


R-FAQ 7.10
:
http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-do-I-convert-factors-to-numeric_003f

--  
David Winsemius
On Feb 27, 2009, at 2:56 PM, Alexy Khrabrov wrote:

> I want to produce a dataframe with integer columns for elements of  
> string pairs:
>
> pairs <- c("10 21","23 45")
> pairs.split <- lapply(pairs,function(x)strsplit(x," "))
> pdf <- as.data.frame(pairs.split)
> names(pdf) <- c("p","q")
>
> -- at this point things look good, except the columns are factors,  
> as I didn't change the default stringsAsFactors parameter to the  
> as.data.frame.
>
> Now if I want to convert columns to integers, I get
>
> > typeof(pdf$p)
> [1] "integer"
> > pdf$p
> [1] 10 21
> Levels: 10 21
> > as.integer(pdf$p)
> [1] 1 2
>
> -- being factor levels instead of the original values.  I could have  
> used stringsAsFactors=F and then convert the strings to integers  
> with as.integer all the same; what other ways are there -- e.g., is  
> there a way to convert integer-looking factors to integers directly,  
> without substituting levels?
>
> Cheers,
> Alexy
>
> ______________________________________________
> R-help at r-project.org 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