[R] factors to integers preserving value in a dataframe

Alexy Khrabrov deliverable at gmail.com
Fri Feb 27 20:56:02 CET 2009


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




More information about the R-help mailing list