rapply

Published by onesixx on

recusive lapply

rapply(object, f, classes = “ANY”, deflt = NULL,
how = c(“unlist”, “replace”, “list”), …)

DD <- list(list(a = pi, b = list(c = 1L)), d = "a test")
DD <- list(
\t   list(\t
\t\t a = pi, 
\t\t b = list(c = 1L)
\t   ), 
\t   d = "a test"
     )

> DD
[[1]]
[[1]]$a
[1] 3.141593

[[1]]$b
[[1]]$b$c
[1] 1

$d
[1] "a test"

basic modes.
how = “replace” , each element of object which is not itself list-like and has a class included in classes is replaced by the result of applying f to the element.

how = “list” or how = “unlist”, conceptually object is copied, all non-list elements which have a class included in classes are replaced by the result of applying f to the element and all others are replaced by deflt. Finally, if how = “unlist”, unlist(recursive = TRUE) is called on the result.

> rapply(DD, function(x) x)
                 a                b.c                  d 
"3.14159265358979"                "1"           "a test" 
> rapply(DD, function(x) x, how="unlist")  # above same (vector)
> rapply(DD, function(x) x, how="list")    # No Change
> rapply(DD, function(x) x, how="replace") # No Change
> rapply(DD, sqrt, classes = "numeric", how = "replace")
[[1]]
[[1]]$a
[1] 1.772454

[[1]]$b
[[1]]$b$c
[1] 1

$d
[1] "a test"

> rapply(DD, sqrt, classes = "numeric", how = "list")
[[1]]
[[1]]$a
[1] 1.772454

[[1]]$b
[[1]]$b$c
NULL

$d
NULL

> rapply(DD, sqrt, classes = "numeric", how = "unlist")
       a 
1.772454 
> rapply(DD, nchar)
> rapply(DD, nchar, how="unlist")  # same
  a b.c   d 
 16   1   6 
> rapply(DD, nchar, classes="character")
d 
6 
> rapply(DD, nchar, classes="character", deflt=NA_integer_)
> rapply(DD, nchar, classes="character", deflt=NA_integer_, how = "unlist")
  a b.c   d 
 NA  NA   6

> rapply(DD, nchar, classes = "character",  how = "list")
[[1]]
[[1]]$a
NULL

[[1]]$b
[[1]]$b$c
NULL

$d
[1] 6
> rapply(DD, nchar, classes="character", deflt=NA_integer_, how = "list")
[[1]]
[[1]]$a
[1] NA

[[1]]$b
[[1]]$b$c
[1] NA

$d
[1] 6
## with expression() / list():
E  <- expression(list(a = pi, b = expression(c = C1 * C2)), d = "a test")
LE <- list(expression(a = pi, b = expression(c = C1 * C2)), d = "a test")
rapply(E, nchar, how="replace") # "expression(c = C1 * C2)" are 23 chars
rapply(E, nchar, classes = "character", deflt = NA_integer_, how = "unlist")
rapply(LE, as.character) # a "pi" | b1 "expression" | b2 "C1 * C2" ..
rapply(LE, nchar)        # (see above)
stopifnot(exprs = {
  identical(E , rapply(E , identity, how = "replace"))
  identical(LE, rapply(LE, identity, how = "replace"))
})
# }

Categories: R Reshaping

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x