Alexander Shenkin
2009-Aug-21 15:47 UTC
[R] Convert list to data frame while controlling column types
Hello all, I have a list which I'd like to convert to a data frame, while maintaining control of the columns' data types (akin to the colClasses argument in read.table). My numeric columns, for example, are getting converted to factors by as.data.frame. Is there a way to do this, or will I have to do as I am doing right now: allow as.data.frame to coerce column-types as it sees fit, and then convert them back manually? Thanks, Allie
Steve Lianoglou
2009-Aug-21 15:54 UTC
[R] Convert list to data frame while controlling column types
Hi Allie, On Aug 21, 2009, at 11:47 AM, Alexander Shenkin wrote:> Hello all, > > I have a list which I'd like to convert to a data frame, while > maintaining control of the columns' data types (akin to the colClasses > argument in read.table). My numeric columns, for example, are getting > converted to factors by as.data.frame. Is there a way to do this, or > will I have to do as I am doing right now: allow as.data.frame to > coerce > column-types as it sees fit, and then convert them back manually?This doesn't sound right ... are there characters buried in your numeric columns somewhere that might be causing this? I'm pretty sure this shouldn't happen, and a small test case here goes along with my intuition: R> a <- list(a=1:10, b=rnorm(10), c=LETTERS[1:10]) R> df <- as.data.frame(a) R> sapply(df, is.factor) a b c FALSE FALSE TRUE Can you check to see if your data's wonky somehow? -steve -- Steve Lianoglou Graduate Student: Computational Systems Biology | Memorial Sloan-Kettering Cancer Center | Weill Medical College of Cornell University Contact Info: http://cbio.mskcc.org/~lianos/contact
David Winsemius
2009-Aug-21 18:15 UTC
[R] Convert list to data frame while controlling column types
On Aug 21, 2009, at 11:47 AM, Alexander Shenkin wrote:> Hello all, > > I have a list which I'd like to convert to a data frame, while > maintaining control of the columns' data types (akin to the colClasses > argument in read.table). My numeric columns, for example, are getting > converted to factors by as.data.frame. Is there a way to do this,Perhaps this may help: as.data.frame(xlist,stringsAsFactors = FALSE) > ll <-list( a=1:10, b=as.character(1:10) ) > str( as.data.frame(ll) ) 'data.frame': 10 obs. of 2 variables: $ a: int 1 2 3 4 5 6 7 8 9 10 $ b: Factor w/ 10 levels "1","10","2","3",..: 1 3 4 5 6 7 8 9 10 2 > str( as.data.frame(ll, stringsAsFactors=FALSE) ) 'data.frame': 10 obs. of 2 variables: $ a: int 1 2 3 4 5 6 7 8 9 10 $ b: chr "1" "2" "3" "4" ... This will not force conversion to numeric if they started life as character. Maybe you need to use lapply with as.numeric? David Winsemius, MD Heritage Laboratories West Hartford, CT