r强制将列表添加到数据框

问题描述 投票:0回答:1

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

该列表是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个回答
0
投票

首先。 Hmsic有错别字,是Hmisc

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

而且我不认为有elegant函数可以制作your数据框。

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

# 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()功能是否按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.