[R] Convert list to data frame while controlling column types

David Winsemius dwinsemius at comcast.net
Fri Aug 21 20:15:31 CEST 2009


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




More information about the R-help mailing list