> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Jeroen Ooms
> Sent: Saturday, September 05, 2009 9:20 AM
> To: r-help at r-project.org
> Subject: [R] Convert dataframe to array of records
>
>
> I would like to convert a dataframe to an array of lists, one
> for every
> record. A natural choide is apply as.list to the rows.
> However, as it seems,
> as.list() automatically converts all list elements to the
> same datatype.
No, apply itself converts the whole data.frame to a matrix,
forcing the columns to one data type. I think that apply()
is rarely a good tool for working with data.frames.
You will have to do something like
rowsOfDataFrame <- function(dataframe)
lapply(seq_len(nrow(dataframe)), function(i)dataframe[i,])
or perhaps as.list(dataframe[i,]) if you really want to get rid
of the data.frame-ness.
Bill Dunlap
TIBCO Software Inc - Spotfire Division
wdunlap tibco.com
> Eg:
>
> myData <- data.frame(a="foo",b=as.logical(rbinom(10,1,.5)));
> apply(myData,1,as.list);
>
> In this output, all boolean values have been converted to
> character strings.
> I don't understand why this happens; a list does not require
> that every
> element is of the same datatype. Is there an easy way (ie
> avoid for-loops
> etc) to convert the dataframe to an array of records, while
> keeping the
> datatypes for every field?
>
> -----
> Jeroen Ooms * Dept. of Methodology and Statistics * Utrecht
> University
>
> Visit http://www.jeroenooms.com www.jeroenooms.com to
> explore some of my
> current projects.
>
>
>
>
>
>
> --
> View this message in context:
> http://www.nabble.com/Convert-dataframe-to-array-of-records-tp
25310023p25310023.html> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>