R - rapply(): recursively apply function to list

25 Dec 2018

Other apply functions:

rapply

1) recursively apply a function to a list. 2) apply a function to only those elements in a list (or columns in a data frame) that belong to a specified class.

For example, let’s say we have a data frame with a mix of categorical and numeric variables, but we want to evaluate a function only on the numeric variables.

<a href=https://www.r-bloggers.com/those-other-apply-functions>https://www.r-bloggers.com/those-other-apply-functions</a>

rapply(object, f, classes = "ANY", deflt = NULL,
       how = c("unlist", "replace", "list"), ...)

# object    = A list.
# f	        = A function of a single argument.
# classes	= A character vector of class names, or "ANY" to match any class.
# deflt	    = The default result (not used if how = "replace").
# how	    = A character string partially matching the three possibilities.
# ...	    = additional arguments passed to the call to f.

# how = "replace"
# => each element of the list which is not itself a list and has a class included in classes is replaced by the result of applying f to the element.

# how = "list" or how = "unlist"
# => the list 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. 
# => if how = "unlist", unlist(recursive = TRUE) is called on the result.

# returns a vector if how = "unlist", otherwise a list of similar structure to object.

X <- list(list(a = pi, b = list(c = 1:1)), d = "a test")
# [[1]]
#  [[1]]$a
#   [1] 3.141593
#   [[1]]$b
#    [[1]]$b$c
#     [1] 1
# $d
# [1] "a test"

rapply(X, function(x) x, how = "replace")
# (-> return a list identical to X)

rapply(X, sqrt, classes = "numeric", how = "replace")
# [[1]]
# [[1]]$a
# [1] 1.772454
# [[1]]$b
# [[1]]$b$c
# [1] 1
# $d
# [1] "a test"

rapply(X, nchar, classes = "character",
       deflt = as.integer(NA), how = "list")
# [[1]]
# [[1]]$a
# [1] NA
# [[1]]$b
# [[1]]$b$c
# [1] NA
# $d
# [1] 6

rapply(X, nchar, classes = "character",
        deflt = 0, how = "list")
# [[1]]
# [[1]]$a
# [1] 0
# [[1]]$b
# [[1]]$b$c
# [1] 0
# $d
# [1] 6
rapply(X, nchar, classes = "character",
       deflt = as.integer(NA), how = "unlist")
# a b.c   d 
# NA  NA   6
 
rapply(X, nchar, classes = "character", how = "unlist")
# d 
# 6 

rapply(X, log, classes = "numeric", how = "replace", base = 2)
# [[1]]
# [[1]]$a
# [1] 1.651496
# [[1]]$b
# [[1]]$b$c
# [1] 1
# $d
# [1] "a test"

[ R  apply  list  function  ]