Learn R Programming

listr (version 0.1.0)

list_insert: Insert an element into a list.

Description

Insert an element into a list.

Usage

list_insert(in_list, item, index, name = NULL, pad = FALSE)

list_append(in_list, item, name = NULL)

list_prepend(in_list, item, name = NULL)

Value

A list, the same as `in_list` but with `item` added at `index`.

Arguments

in_list

The list to work on.

item

The item to add to the list.

index

The index to insert at.

name

Optional name for the new item.

pad

Add `NULL` elements for too large indices?

Details

The `index` behaves in the way that everything including the specified index will be moved one position forward. Thus, if you insert at index 2, the old item at index 2 will be moved to index 3. If `index` is larger than the length of `in_list` the default behaviour is to just add the new item to the end of the list, however if you specify `pad = TRUE` then as many `NULL` elements as needed are added to the list to insert `item` at the specified location.

The functions `list_append` and `list_prepend` exist as a simple short-cut for appending and prepending to a list.

Examples

Run this code
my_list <- list(foo1 = 1:10, foo2 = LETTERS[1:10])
list_insert(my_list, rnorm(3), 2, name = "bar")

Run the code above in your browser using DataLab