如何展开列表列表?

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)生成一个 PlainTextDocument 的平面列表,这仍然给我留下了逐个元素向 c提供列表元素的问题

84881 次浏览

I expect that unlist(foolist) will help you. It has an option recursive which is TRUE by default.

So unlist(foolist, recursive = FALSE) will return the list of the documents, and then you can combine them by:

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

do.call just applies the function c to the elements of the obtained list

Here's a more general solution for when lists are nested multiple times and the amount of nesting differs between elements of the lists:

 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)
}
}

Here's another method that worked for my list of lists.

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

Or take a look at new functions in tidyr which work well.

rectangle a nested list into a tidy tibble

rectangling

    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)