在 R 编程中递归地将函数应用于列表 - rapply()函数
R 语言中的rapply()
函数用于递归地将函数应用于列表。
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
rapply()
函数中的模式有两种基本类型。如果how = “replace” ,列表对象的每个元素本身不是一个列表,并且在 classes 中包含一个类,则列表的每个元素都被应用于该元素的函数f的结果值替换。
如果how = “list”或how = “unlist” ,则复制列表对象,并且包含在类中的所有非列表元素都将替换为应用于该元素的函数f的结果值,而所有其他元素都将替换为deflt 。
示例 1:使用替换模式
# 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")
输出:
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"
示例 2:使用列表模式
# 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")
输出:
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
示例 3:使用非列表模式
# 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")
输出:
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