nest: Nest a value in a list

Description Usage Arguments Details Value Examples

View source: R/nest.R

Description

Embed a value into a list (possibly named) that has an arbitrary number of levels.

Usage

1
nest(levels, value = NULL)

Arguments

levels

[integer(1) | character]

Either the desired number of levels or their explicit names. For the latter, the last element of levels is the name of the last node. It is not considered to be a level. Any integer passed to this argument must be greater than or equal to 0.

value

[any]

Value to be nested.

Details

Function nest() embeds (nests) value into a tree. Each node is a list, except for the last one which is set equal to value. Nodes are named if non-empty strings are passed to levels. See examples.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<level 0> (top-level)
│
└── <level 1>
    │
    └── <level 2>
        │
        └── <...>
            │
            └── <terminal node>
                │
                └── value

As an example, calling nest(c("lvl1", "lvl2", "terminal_node")) yields the following tree.

1
2
3
4
5
6
7
list(lvl1 =
│
└── list(lvl 2 =
    │
    └── list(terminal_node =
        │
        └── value)))

Passing either 0L or character(0L) to argument levels yields a degenerate case: it implies value should not be nested into any list.

Value

A list, possibly named if levels is a character vector, with a number of levels prescribed by levels. If levels is either 0 or character(0L), nest() simply returns value. See details.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
## Nest a value into a list of 0, 1, 2, or 3 levels.
nest(0L, "my nested value")
nest(1L, "my nested value")
nest(2L, "my nested value")
nest(3L, "my nested value")

## Nest a value into a complex tree of 100 levels.
nest(100L, "deeply nested value")

## Nest a NULL value into a tree of named lists.
x <- nest(c("level_1", "level_2", "level_3", "terminal_node"))
y <- list(
    level_1 = list(
        level_2 = list(
            level_3 = list(terminal_node = NULL))))

identical(x, y) # TRUE

## You can nest any R object, even other lists.
nest(3L, value = nest(3L, value = "Hey!"))

jeanmathieupotvin/dotprofile documentation built on Dec. 20, 2021, 10:08 p.m.