list.clean: Clean a list by a function

Description Usage Arguments Details Examples

View source: R/list.clean.R

Description

This function removes all elements evaluated to be TRUE by an indicator function. The removal can be recursive so that the resulted list surely does not include such elements in any level.

Usage

1
list.clean(.data, fun = is.null, recursive = FALSE)

Arguments

.data

A list or vector to operate over.

fun

A character or a function that returns TRUE or FALSE to indicate if an element of .data should be removed.

recursive

logical. Should the list be cleaned recursively? Set to FALSE by default.

Details

Raw data is usually not completely ready for analysis, and needs to be cleaned up to certain standards. For example, some data operations require that the input does not include NULL values in any level, therefore fun = "is.null" and recursive = TRUE can be useful to clean out all NULL values in a list at any level.

Sometimes, not only NULL values are undesired, empty vectors or lists are also unwanted. In this case, fun = function(x) length(x) == 0L can be useful to remove all empty elements of zero length. This works because length(NULL) == 0L, length(list()) == 0L and length(numeric()) == 0L are all TRUE.

Examples

1
2
3
4
x <- list(a=NULL,b=list(x=NULL,y=character()),d=1,e=2)
list.clean(x)
list.clean(x, recursive = TRUE)
list.clean(x, function(x) length(x) == 0L, TRUE)

Example output

$b
$b$x
NULL

$b$y
character(0)


$d
[1] 1

$e
[1] 2

$b
$b$y
character(0)


$d
[1] 1

$e
[1] 2

$d
[1] 1

$e
[1] 2

rlist documentation built on Sept. 5, 2021, 5:30 p.m.