如何展平列表列表?

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

tm
包扩展了
c
,因此,如果给定一组
PlainTextDocument
,它会自动创建一个
Corpus
。不幸的是,似乎每个
PlainTextDocument
都必须单独指定。

例如如果我有:

foolist <- list(a, b, c); # where a,b,c are PlainTextDocument objects

我这样做是为了获得

Corpus

foocorpus <- c(foolist[[1]], foolist[[2]], foolist[[3]]);

我有一个

'PlainTextDocument
列表,如下所示:

> str(sectioned)
List of 154
 $ :List of 6
  ..$ :Classes 'PlainTextDocument', 'TextDocument', 'character'  atomic [1:1] Developing assessment models   Developing models
  .. .. ..- attr(*, "Author")= chr "John Smith"
  .. .. ..- attr(*, "DateTimeStamp")= POSIXlt[1:1], format: "2013-04-30 12:03:49"
  .. .. ..- attr(*, "Description")= chr(0) 
  .. .. ..- attr(*, "Heading")= chr "Research Focus"
  .. .. ..- attr(*, "ID")= chr(0) 
  .. .. ..- attr(*, "Language")= chr(0) 
  .. .. ..- attr(*, "LocalMetaData")=List of 4
  .. .. .. ..$ foo           : chr "bar"
  .. .. .. ..$ classification: chr "Technician"
  .. .. .. ..$ team          : chr ""
  .. .. .. ..$ supervisor    : chr "Bill Jones"
  .. .. ..- attr(*, "Origin")= chr "Smith-John_e.txt"

#etc., all sublists have 6 elements

所以,要将我所有的

PlainTextDocument
变成
Corpus
,这会起作用:

sectioned.Corpus <- c(sectioned[[1]][[1]], sectioned[[1]][[2]], ..., sectioned[[154]][[6]])

有人可以建议一个更简单的方法吗?

预计到达时间:

foo<-unlist(foolist, recursive=FALSE)
会生成一个纯文本文档的平面列表,这仍然给我留下了将列表逐个元素输入到
c

的问题
r list tm
4个回答
110
投票

我希望

unlist(foolist)
能帮助你。它有一个选项
recursive
,默认为
TRUE

因此

unlist(foolist, recursive = FALSE)
将返回文档列表,然后您可以通过以下方式组合它们:

do.call(c, unlist(foolist, recursive=FALSE))

do.call
只是将函数
c
应用于获得的列表的元素


34
投票

当列表嵌套多次并且列表元素之间的嵌套数量不同时,这是一个更通用的解决方案:

 flattenlist <- function(x){  
  morelists <- sapply(x, function(xprime) class(xprime)[1]=="list")
  out <- c(x[!morelists], unlist(x[morelists], recursive=FALSE))
  if(sum(morelists)){ 
    Recall(out)
  }else{
    return(out)
  }
}

12
投票

这是另一种适用于我的列表的方法。

df <- as.data.frame(do.call(rbind, lapply(foolist, as.data.frame)))

或者看看 tidyr 中运行良好的新功能。

将嵌套列表矩形化为整洁的小标题

矩形化

    lst <-  list(
      list(
        age = 23,
        gender = "Male",
        city = "Sydney"
      ),
      list(
        age = 21,
        gender = "Female",
        city = "Cairns"
      )
    )
      
    tib <- tibble(lst)  %>% 
      unnest_wider(lst)

df <- as.data.frame(tib)

0
投票

我用这个:

flatt <- 
\ (xss, flatf = c) 
    xss |> Reduce (\(a,b) flatf (a,b) , x = _) ;

演示:

list (list (1,0,3),list (2,4),list (3,6,5)) |> flatt(c)

# or

list (list (1,0,3),list (2,4),list (3,6,5)) |> flatt()

它会给出与

list (1,0,3,2,4,3,6,5)
相同的结果。

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