rapply2: Recursively apply a function to a list

View source: R/utils.R

rapply2R Documentation

Recursively apply a function to a list

Description

Iterates over a (possibly nested) list and applies a function if a specific class is found.

Usage

rapply2(
  x,
  FUN,
  classes = "ANY",
  ...,
  check.nested = "list" %in% classes,
  skip.null = TRUE
)

Arguments

x

a list

FUN

the function to be applied to each classes element of x

classes

a character vector of class names or "ANY" to apply to every non-list element of x

...

additional arguments passed to FUN

check.nested

logical; if TRUE, for nested lists, rapply2 will continue to walk down the list rather than stop at the first list (only if "list" %in% classes)

skip.null

logical; if TRUE (default), NULL elements of x will be skipped before FUN can be applied

Value

A list having the same structure as x with FUN applied to all (including nested) elements with a class matching classes.

See Also

rapply

Examples

ll <- list(list(list(head(cars), list(head(cars)))), letters[1:4],
           factor(1:4), 1:3, head(cars))
rapply2(ll, class)
rapply2(ll, log, classes = 'data.frame', base = 10)


## note that data.frames are not considered lists unless explicit
str(rapply2(ll, unlist, classes = 'list'))
str(rapply2(ll, unlist, classes = c('list', 'data.frame')))

## compare
str(rapply2(ll, unlist))


## remove all elements by name
f <- function(x) if (!is.null(names(x))) x[names(x) %ni% 'id'] else x
ll <- list(a = list(id = 1, name = 'a-1'),
           b = list(id = 1, list(id = 2, name = 'b-2'),
                    list(id = 3, name = 'b-3', id = 3)),
           c = list(id = 4),
           id = 'n/a')

## compare
str(rapply2(ll, f, 'list', check.nested = FALSE))
str(rapply2(ll, f, 'list', check.nested = TRUE))


## use skip.null = FALSE to apply FUN to NULL list elements
ll <- list(NULL, 1, list(2, NULL, list(3, NULL)))
rapply2(ll, function(x) if (is.null(x)) NA else x)
rapply2(ll, function(x) if (is.null(x)) NA else x, skip.null = FALSE)


raredd/rawr documentation built on March 4, 2024, 1:36 a.m.