【问题标题】:r force a list to dataframer 强制列表到数据框
【发布时间】:2020-04-24 03:57:13
【问题描述】:

我正在尝试获取嵌套列表并将内容存储到数据框中。

该列表是Hmsic::describe 函数的输出。这是一个测试用例。

  list <- Hmisc::describe(iris)

这个列表有多个对象,有些是嵌套的。我只对列表中的一部分对象感兴趣。

unlist(list [[1]])[1:4]
unlist(list [[2]])[1:4]
unlist(list [[3]])[1:4]
unlist(list [[4]])[1:4]

预期的输出将有两个数据框,并将以下列表对象转换为列

对于基于连续变量的列表对象,预期的数据框将如下所示

   description               n       missing  distinct    lowest                       highest
   Sepal.Length            150        0            35     4.3, 4.4, 4.5, 4.6, 4.7      7.3, 7.4, 7.6, 7.7, 7.9
   Sepal.Width             150        0            23     2.0, 2.2, 2.3, 2.4, 2.5      3.9, 4.0, 4.1, 4.2, 4.4
   Petal.Length            150        0            43     1.0, 1.1, 1.2, 1.3, 1.4      6.3, 6.4, 6.6, 6.7, 6.9
   Petal.Width             150        0            22     0.1, 0.2, 0.3, 0.4, 0.5      2.1, 2.2, 2.3, 2.4, 2.5

对于基于离散变量的列表对象,预期的数据框将如下所示

      description      n       missing   distinct   Values                           Frequency          
      Species        150        0        3          setosa, versicolor,  virginica   50,50,50

对完成这一点的任何帮助。谢谢。

【问题讨论】:

    标签: r list nested-lists


    【解决方案1】:

    首先。 Hmsic 有错字,是Hmisc

    您可以使用$ 访问列表对象的元素。

    我不认为有 优雅 功能可以制作 您的 数据框。

    这是连续数据帧的最小示例。

    # install.packages('Hmisc')
    
    listObj <- Hmisc::describe(iris)
    
    dataframe <- c()
    
    for(i in 1:4){
      subList <- listObj[[i]]
    
      rowadd <- c(
        subList$descript,
        subList$counts[['n']],
        subList$counts[['missing']],
        subList$counts[['distinct']],
        as.character(unname(paste(subList$extremes[1:5], collapse = ', '))),
        as.character(unname(paste(subList$extremes[6:10], collapse = ', ')))
      )
    
      dataframe <- rbind(dataframe, rowadd)
    
    }
    dataframe <- data.frame(dataframe, row.names = NULL)
    colnames(dataframe) <- c('description', 'n', 'missing', 'distinct', 'lowest', 'highset')
    

    编辑:R 4.0 现在支持将变量列表更改为 data.frame

    检查list2DF() 函数是否按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2020-03-22
      • 1970-01-01
      • 2012-09-12
      • 2021-05-24
      • 1970-01-01
      • 2021-12-27
      相关资源
      最近更新 更多