[R] list to data frame by rows ...
Peter Dalgaard BSA
p.dalgaard at biostat.ku.dk
Wed May 9 22:05:29 CEST 2001
Douglas Bates <bates at stat.wisc.edu> writes:
> Johann Petrak <johann at ai.univie.ac.at> writes:
>
> > Ugh, newbie question ... :
> >
> > I have a list of vectors of equal size, like
> > list(c(1,2,3),c(4,5,6))
> > and want to convert this into a data frame row-wise:
> >
> > 1 1 4
> > 2 2 5
> > 3 3 6
> >
> > Whats the elegant/R-way to do this?
>
> In general the cbind function is used to bind columns into an array.
> If you want to invoke it on a list of arguments you can use do.call to
> create the function call. Combining these gives
>
> > mylist <- list(c(1,2,3),c(4,5,6))
> > do.call("cbind", mylist)
> [,1] [,2]
> [1,] 1 4
> [2,] 2 5
> [3,] 3 6
However, if a data frame is desired all you really need is
as.data.frame:
> l <- list(c(1,2,3),c(4,5,6))
> as.data.frame(l)
c.1..2..3. c.4..5..6.
1 1 4
2 2 5
3 3 6
(or data.frame(l) for that matter -- there's a subtle distinction
which escapes me for the moment...)
As, seen, there's a gotcha in the generation of names (try
as.data.frame(list(rnorm(100),rnorm(100))) for a more extreme
example). It would be wiser to set the names first, as in
> names(l)<-c("V1","V2"); as.data.frame(l)
V1 V2
1 1 4
2 2 5
3 3 6
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list