我最近为此实现了一些递归实用程序函数。但是他们不检查前提条件(等长,元素的可和性)。
编辑:我已经修复了 cmets 中提到的问题。 for 循环被高阶函数所取代,该函数具有更好的错误行为。该函数还处理更复杂的列表结构,例如包含其他包含数字元素的列表的列表。它比 OP 要求的更多(也更复杂),但我认为值得保留,以防有人需要递归解决方案。
sum_numeric_lists <- function(...){
lists <- list(...)
if (length(unique(sapply(lists, length))) > 1) {
stop("lists are not of equal length")
}
Map(function(...) {
elems <- list(...)
if (length(unique(sapply(elems, class))) > 1) {
stop("corresponding elements have different types")
}
if (is.list(elems[[1]])) {
sum_numeric_lists(...)
} else if(is.numeric(elems[[1]])){
Reduce(`+`, elems)
} else {
warning("lists contain types other than numeric, which are preserved as NULL elements")
NULL
}
}, ...)
}
devide_numeric_list_by <- function(l, divisor){
lapply(X = l, FUN = function(elem) {
if (is.list(elem)) {
devide_numeric_list_by(elem, divisor)
} else if(is.numeric(elem)){
elem / divisor
} else {
warning("lists contain types other than numeric, which are preserved as NULL elements")
NULL
}
})
}
avg_numeric_lists <- function(...){
sum_l <- sum_numeric_lists(...)
devide_numeric_list_by(sum_l, length(list(...)))
}
一些测试:
avg_numeric_lists()
avg_numeric_lists(NULL)
avg_numeric_lists(list())
avg_numeric_lists(list(NULL))
avg_numeric_lists(list(1))
avg_numeric_lists(list(list(1)))
list1 <- list(m_first_lvl = matrix(sample(1:10, 20, replace = T), nrow=4, ncol=5),list(m_sec_lvl = matrix(sample(1:10, 6, replace = T), nrow=3, ncol=2)),"not_a_list_or_numeric",a_number = 1)
list2 <- list(m_first_lvl = matrix(sample(1:10, 20, replace = T), nrow=4, ncol=5),list(m_sec_lvl = matrix(sample(1:10, 6, replace = T), nrow=3, ncol=2)),"not_a_list_or_numeric",a_number = 2)
list3 <- list(m_first_lvl = matrix(sample(1:10, 20, replace = T), nrow=4, ncol=5),list(m_sec_lvl = matrix(sample(1:10, 6, replace = T), nrow=3, ncol=2)),"not_a_list_or_numeric",a_number = 3)
avg_numeric_lists(list1, list2, list3)
在全局环境中的所有列表上调用它(如 rawr 所建议的):
do.call(what = avg_numeric_lists, args = mget(ls(pattern = '^list\\d+$')))