【问题标题】:How to fill in a dataframe with lists of vectors?如何用向量列表填充数据框?
【发布时间】:2020-11-19 12:43:52
【问题描述】:

我有一个向量列表LIST1 如下:

[[1]]
[1] 1 2 3 4 5 6 7

[[2]]
[1] 2 3 1 5

[[3]]
[1] 7 12 61 12

我还有另一个向量列表LIST2

[[1]]
[1] 32 12 51 12

[[2]]
[1] 51 11 1

[[3]]
integer(0)

我的目标是将两个列表转换为一个数据框,其中每个向量都是一个单元格,因此该数据框将由两行和 3 列组成:

             V1               V2           V3
LIST1    1,2,3,4,5,6,7      2,3,1,5     7,12,61,12
LIST2    32,12,51,12        51,11,1        NA

这是我目前的代码:

    my_dataframe = data.frame(matrix(vector(),nb_of_lists,length(LIST1))
    
    list_all = list(LIST1,LIST2) # put both lists in one list
    n = length(LIST1) # LIST1 and LIST2 have the same length so it doesn't matter
    
    for(x in 1:nb_of_lists)
    {
       for(y in 1:n))
         {
            my_dataframe[x,y]= list_all[[x]][y]
         }
    }

但它不起作用,我收到的主要是这条警告消息:

In `[<-.data.frame`(`*tmp*`, , i, value = list(c(L1, L2, L3, :
    replacement element 1 has 7 rows to replace 1 rows

任何帮助将不胜感激。

【问题讨论】:

    标签: r list dataframe vector


    【解决方案1】:

    您将需要班级列表的列。这是一种方法:

    out <- as.data.frame(mapply(function(x,y) list(x,y), LIST1, LIST2))
    str(out)
    # 'data.frame': 2 obs. of  3 variables:
    #  $ V1:List of 2
    #   ..$ : int  1 2 3 4 5 6 7
    #   ..$ : int  32 12 51 12
    #  $ V2:List of 2
    #   ..$ : int  2 3 1 5
    #   ..$ : int  51 11 1
    #  $ V3:List of 2
    #   ..$ : int  7 12 61 12
    #   ..$ : int
    

    第二种(也是更有效的)解决方案:

    out <- data.table::setDF(Map(function(x,y) list(x,y), LIST1, LIST2))
    

    可重现的数据(请下次自行分享)

    LIST1 <- list(1:7, c(2L,3L,1L,5L), c(7L,12L,61L,12L)) 
    LIST2 <- list(c(32L,12L,51L,12L), c(51L, 11L, 1L), integer())
    

    【讨论】:

      猜你喜欢
      • 2015-06-25
      • 2013-10-22
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 2011-11-07
      • 2021-06-06
      相关资源
      最近更新 更多