Recursively apply a Function to a List in R Programming – rapply() function
rapply()
function in R Language is used to recursively apply a function to a list.
Syntax:
rapply(object, f, classes = “ANY”, deflt = NULL, how = c(“unlist”, “replace”, “list”))Parameters:
object: represents list or an expression
f: represents function to be applied recursively
classes: represents class name of the vector or “ANY” to match any of the class
deflt: represents default result when how is not “replace”
how: represents modes
The modes in rapply()
function are of 2 basic types. If how = “replace”, each element of the list object which is not itself is a list and has a class included in classes then each element of the list is replaced by the resulting value of the function f applied to the element.
If how = “list” or how = “unlist”, list object is copied and all non-list elements which are included in classes are replaced by the resulting value of the function f applied to the element and all other are replaced by deflt.
Example 1: Using replace mode
# Defining a list ls <- list (a = 1:5, b = 100:110, c = c ( 'a' , 'b' , 'c' )) # Print whole list cat ( "Whole List: \n" ) print (ls) # Using replace mode cat ( "Using replace mode:\n" ) rapply (ls, mean, how = "replace" , classes = "integer" ) |
Output:
Whole List: $a [1] 1 2 3 4 5 $b [1] 100 101 102 103 104 105 106 107 108 109 110 $c [1] "a" "b" "c" Using replace mode: $a [1] 3 $b [1] 105 $c [1] "a" "b" "c"
Example 2: Using list mode
# Defining a list ls <- list (a = 1:5, b = 100:110, c = c ( 'a' , 'b' , 'c' )) # Print whole list cat ( "Whole List: \n" ) print (ls) # Using list mode cat ( "Using list mode:\n" ) rapply (ls, mean, how = "list" , classes = "integer" ) |
Output:
Whole List: $a [1] 1 2 3 4 5 $b [1] 100 101 102 103 104 105 106 107 108 109 110 $c [1] "a" "b" "c" Using list mode: $a [1] 3 $b [1] 105 $c NULL
Example 3: Using unlist mode
# Defining a list ls <- list (a = 1:5, b = 100:110, c = c ( 'a' , 'b' , 'c' )) # Print whole list cat ( "Whole List: \n" ) print (ls) # Using unlist mode cat ( "Using unlist mode:\n" ) rapply (ls, mean, how = "unlist" , classes = "integer" ) |
Output:
Whole List: $a [1] 1 2 3 4 5 $b [1] 100 101 102 103 104 105 106 107 108 109 110 $c [1] "a" "b" "c" Using unlist mode: a b 3 105
Please Login to comment...