Learn R Programming

cheapr (version 1.1.0)

lengths_: List utilities

Description

Functions to help work with lists.

Usage

lengths_(x, names = FALSE)

unlisted_length(x)

new_list(length = 0L, default = NULL)

Value

lengths_() returns the list lengths.

unlisted_length() is an alternative to length(unlist(x)).

new_list() is like vector("list", length) but also allows you to specify a default value for each list element. This can be useful for initialising with a catch-all value so that when you unlist you're guaranteed a list of length >= to the specified length.

Arguments

x

A list.

names

Should names of list elements be added? Default is FALSE.

length

Length of list.

default

Default value for each list element.

Examples

Run this code
library(cheapr)
l <- list(1:10,
          NULL,
          list(integer(), NA_integer_, 2:10))

lengths_(l) # Faster lengths()
unlisted_length(l) # length of vector if we unlist
paste0("length: ", length(print(unlist(l))))

unlisted_length(l) - na_count(l) # Number of non-NA elements

# We can create and initialise a new list with a default value
l <- new_list(20, 0L)
l[1:5]
# This works well with vctrs_list_of objects

Run the code above in your browser using DataLab