Re: [R] converting a list to a data.frame

From: Stephen Tucker <brown_emu_at_yahoo.com>
Date: Tue 03 Apr 2007 - 12:18:05 GMT


You can concatenate a series of NA's to match the length of your longest element.

(1) exampDat is example data
(2) max(rapply(exampDat,length)) is length of longest element
(3) function(x,m) will do the concatenation
(4) sapply() will return each list element as a column of a data frame
(5) t() will transpose it so you get it in row format (and convert it to a
matrix.

then you can use write() or write.table() to export your file to a text file.

exampDat <- list(x=1:2,y=1:3,z=1:4)
mat <- t(sapply(exampDat,

                function(x,m) c(x,rep(NA,m-length(x))),
                max(rapply(exampDat,length))))

## use write.table()

Hope this helps.

> Hello,
>
> I have a list with n numerical components of different length (3, 4 or 5
> values in each component of the list); I need to export this as a text
> file where each component of the list will be a row and where missing
> values should fill in the blanks due to the different lengths of the
> components of the list.
> I think that as a first step I should convert my list to a data frame,
> but this is not such a simple task to accomplish: I was thinking of the
> following "for" loop:
>
> X<-data.frame(1,1,1,1,1);
>
> for (i in 1:length(list)) {
>
> X[i,]<-unlist(list[[i]]);
>
> }
>
> Unfortunately, when the number of elements in the components of the list
> are lower than 5 (maximum), I get errors or undesired results. I also
> tried with rbind(), but again I couldn't manage to make it accept rows
> of different length.
>
> Does anybody have any suggestions? Working with lists is very nice, but
> I still have to learn how to transfer them to text files for external
> use.
>
> Thnak you,
>
> Filippo Biscarini
> Wageningen University
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@stat.math.ethz.ch 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.
>
 



Don't pick lemons.

R-help@stat.math.ethz.ch 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. Received on Tue Apr 03 22:27:16 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 03 Apr 2007 - 13:30:43 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.