rapply2 | R Documentation |
Iterates over a (possibly nested) list and applies a function if a specific
class
is found.
rapply2(
x,
FUN,
classes = "ANY",
...,
check.nested = "list" %in% classes,
skip.null = TRUE
)
x |
a list |
FUN |
the function to be applied to each |
classes |
a character vector of |
... |
additional arguments passed to |
check.nested |
logical; if |
skip.null |
logical; if |
A list having the same structure as x
with FUN
applied to
all (including nested) elements with a class matching classes
.
rapply
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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.