[R] factors to integers preserving value in a dataframe

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Fri Feb 27 21:20:09 CET 2009


have a look at R FAQ 7.10, e.g., try

as.numeric(levels(pdf$p))[as.integer(pdf$p)]


Best,
Dimitris


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

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014




More information about the R-help mailing list