Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a list of lists?

Tags:

list

r

tm

The tm package extends c so that, if given a set of PlainTextDocuments it automatically creates a Corpus. Unfortunately, it appears that each PlainTextDocument must be specified separately.

e.g. if I had:

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

I'd do this to get a Corpus:

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

I have a list of lists of 'PlainTextDocuments that looks like this:

> 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 

So, to get all my PlainTextDocuments into a Corpus, this would work:

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

Can anyone suggest an easier way, please?

ETA: foo<-unlist(foolist, recursive=FALSE) produces a flat list of PlainTextDocuments, which still leaves me with the problem of feeding a list element by element to c

like image 210
dnagirl Avatar asked Apr 30 '13 12:04

dnagirl


People also ask

How do I flatten a list of lists in Python?

To flatten a list of lists in Python, use the numpy library, concatenate(), and flat() function. Numpy offers common operations, including concatenating regular 2D arrays row-wise or column-wise. We also use the flat attribute to get a 1D iterator over the array to achieve our goal.

How do you flatten a list of arrays?

You can flatten a NumPy array ndarray with the numpy. label() function, or the ravel() and flatten() methods of numpy.

How do you flatten list list comprehension?

The itertools. from_iterable() method. The result of this function call is passed as the argument for the list() method which converts the sequence into a list. The final flattened list is printed using the code print("Flatten List:",listflat).


1 Answers

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

like image 164
DrDom Avatar answered Sep 28 '22 11:09

DrDom