[R] Convert list of lists <--> data frame

Marc Schwartz marc_schwartz at comcast.net
Wed Jul 23 18:10:37 CEST 2008


on 07/23/2008 09:42 AM Henrique Dallazuanna wrote:
> Try this:
> 
> pats.df <- do.call(rbind, pats)

Henrique,

Take note of the object that results from this:

 > do.call(rbind, pats)
      shape shape.col shape.lty cell.fill back.fill label label.size
[1,] 0     "black"   1         "white"   "white"   1     1
[2,] 0     "black"   1         "pink"    "white"   1     1
[3,] 0     "black"   1         "red"     "white"   1     1
      ref.col  ref.grid scale.max
[1,] "gray80" "yes"    100
[2,] "gray80" "yes"    100
[3,] "gray80" "yes"    100


 > str(do.call(rbind, pats))
List of 30
  $ : num 0
  $ : num 0
  $ : num 0
  $ : chr "black"
  $ : chr "black"
  $ : chr "black"
  $ : num 1
  $ : num 1
  $ : num 1
  $ : chr "white"
  $ : chr "pink"
  $ : chr "red"
  $ : chr "white"
  $ : chr "white"
  $ : chr "white"
  $ : num 1
  $ : num 1
  $ : num 1
  $ : num 1
  $ : num 1
  $ : num 1
  $ : chr "gray80"
  $ : chr "gray80"
  $ : chr "gray80"
  $ : chr "yes"
  $ : chr "yes"
  $ : chr "yes"
  $ : num 100
  $ : num 100
  $ : num 100
  - attr(*, "dim")= int [1:2] 3 10
  - attr(*, "dimnames")=List of 2
   ..$ : NULL
   ..$ : chr [1:10] "shape" "shape.col" "shape.lty" "cell.fill" ...

 > is.data.frame(do.call(rbind, pats))
[1] FALSE

 > class(do.call(rbind, pats))
[1] "matrix"


There is an extra level of manipulation required, as I noted in my reply:

 > str(do.call(rbind, lapply(pats, data.frame)))
'data.frame':	3 obs. of  10 variables:
  $ shape     : num  0 0 0
  $ shape.col : Factor w/ 1 level "black": 1 1 1
  $ shape.lty : num  1 1 1
  $ cell.fill : Factor w/ 3 levels "white","pink",..: 1 2 3
  $ back.fill : Factor w/ 1 level "white": 1 1 1
  $ label     : num  1 1 1
  $ label.size: num  1 1 1
  $ ref.col   : Factor w/ 1 level "gray80": 1 1 1
  $ ref.grid  : Factor w/ 1 level "yes": 1 1 1
  $ scale.max : num  100 100 100


HTH,

Marc



More information about the R-help mailing list