[英]How to flatten a list of lists?
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
s 列表,如下所示:
> 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]])
任何人都可以建議更簡單的方法嗎?
ETA: foo<-unlist(foolist, recursive=FALSE)
生成一個foo<-unlist(foolist, recursive=FALSE)
的平面列表,這仍然給我一個按元素提供列表元素給c
我希望unlist(foolist)
會幫助你。 它有一個選項recursive
,默認情況下為TRUE
。
所以unlist(foolist, recursive = FALSE)
將返回文檔列表,然后您可以通過以下方式組合它們:
do.call(c, unlist(foolist, recursive=FALSE))
do.call
只是將函數c
應用於獲得的列表的元素
當列表多次嵌套並且列表元素之間的嵌套量不同時,這是一個更通用的解決方案:
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)
}
}
這是另一種適用於我的列表列表的方法。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.