collapse provides the following set of functions to efficiently work with lists of R objects:
Search and Identification
ldepthdetermines the level of nesting of the list (i.e. the maximum number of nodes of the list-tree).
has_elemsearches elements in a list using element names, regular expressions applied to element names, or a function applied to the elements, and returns
TRUEif any matches were found.
irreg_elemare recursive versions of the former.
reg_elemextracts the 'regular' part of the list-tree leading to atomic elements in the final nodes, while
irreg_elemextracts the 'irregular' part of the list tree leading to non-atomic elements in the final nodes. (Tip: try calling both on an
lmobject). Naturally for all lists
get_elemextracts elements from a list using element names, regular expressions applied to element names, a function applied to the elements, or element-indices used to subset the lowest-level sub-lists. by default the result is presented as a simplified list containing all matching elements. With the
get_elemcan also be used to subset lists i.e. maintain the full tree but cut off non-matching branches.
Splitting and Transposition
rsplitrecursively splits a vector or data frame into subsets according to combinations of (multiple) vectors / factors - by default returning a (nested) list. If
flatten = TRUE, the list is flattened yielding the same result as
rsplitis also faster than
split, particularly for data frames.
Unlisting / Row-Binding
unlist2defficiently unlists unlistable lists in 2-dimensions and creates a data frame (or data.table) representation of the list. This is done by recursively flattening and row-binding R objects in the list while creating identifier columns for each level of the list-tree and (optionally) saving the row-names of the objects in a separate column.
unlist2dcan thus also be understood as a recursive generalization of
do.call(rbind, l), for lists of vectors, data frames, arrays or heterogeneous objects. A simpler version for non-recursive row-binding lists of lists / data.frames, is also available by
|Checks if list is unlistable
|Level of nesting / maximum depth of list-tree
|Checks if list contains a certain element
|Subset list / extract certain elements
|Top-level subset atomic elements
|Top-level subset list/list-like elements
|Recursive version of
atomic_elem: Subset / extract 'regular' part of list
|Subset / extract non-regular part of list
|Recursively split vectors or data frames / lists
|Transpose lists of lists
|Recursively apply functions to lists of data objects
|Recursively unlist/row-bind lists of data objects in 2D, to data frame or data.table
|Non-recursive binding of lists of lists / data.frames.