R list of lists to data.frame

前端 未结 5 1250
夕颜
夕颜 2020-11-27 19:12

I\'ve got a list of lists, call it listHolder, which has length 5.

Every element in listHolder is a list of numeric data, with 160 or so e

相关标签:
5条回答
  • 2020-11-27 19:26

    This is the easiest solution I've found.

    library(jsonlite)
    library(purrr)
    library(data.table)
    
    dt_list <- map(list_of_lists, as.data.table)
    dt <- rbindlist(dt_list, fill = TRUE, idcol = T)
    
    dt
    
    0 讨论(0)
  • 2020-11-27 19:32

    I think this is easier than the previous solutions:

    mydf = data.frame(x1 = c('a', 'b', 'c'))
    mylist = list(c(4, 5), c(4, 5), c(4, 5))
    mydf$x2 = mylist
    print(mydf)
      x1   x2
    1  a 4, 5
    2  b 4, 5
    3  c 4, 5
    
    0 讨论(0)
  • 2020-11-27 19:39

    The value of nrow needs to be fixed. I fixed your code as follows:

    dd  <-  as.data.frame(matrix(unlist(listHolder), nrow=length(unlist(listHolder[1]))))
    
    0 讨论(0)
  • 2020-11-27 19:43

    This achieves a similar result, but is more intuitive (to me at least)

    #Generate fake data 
    listoflists=list(c(1,'a',3,4),c(5,'b',6,7))
    
    #Convert to a dataframe, transpose, and convert the resulting matrix back to a dataframe
    df= as.data.frame(t(as.data.frame(listoflists)))
    
    #Strip out the rownames if desired
    rownames(df)<-NULL
    
    #Show result
    df
    
    0 讨论(0)
  • 2020-11-27 19:45

    AS @dimitris_ps mentioned earlier, the answer could be:

    do.call(rbind, listHolder)
    

    Since do.call naturally "strips" 1 level of the "list of list", obtaining a list, not a list of lists.

    After that, rbind can handle the elements on the list and create a matrix.

    0 讨论(0)
提交回复
热议问题