Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 42 / 68

Flattening a list

This lesson covers flattening a nested list with R's unlist, with the aim of handling complicated structures simply.

When a list contains further lists, expanding it into one flat vector is called flattening. In R, unlist() does it in a single line.

The sample code runs unlist(nested) on the deeply nested list(1, list(2, 3), list(4, list(5, 6))) to expand it into one vector containing every value. Note that it flattens however many levels deep it goes.

A common early stumble is that unlist always returns a vector. If the original elements included different types (numbers and strings), they are automatically converted to a common type.

In professional work, this is a genuinely useful technique whenever nested data has to be handled as one flat collection.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)