分在最後的列表中的每個元素我最近實施一些遞歸的實用功能。但是他們不檢查前提條件(等長,元素的總結)。
編輯:我有固定在評論中提到的問題。 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+$')))
每個矩陣的位置在每個列表相同的,所以我想每個矩陣添加到同一矩陣 – user3742038
與你的真實結果也不同的變量,比如'list1','list2'名單,.. 。?或者他們存儲在其他列表中? – Julius
它們存儲在單獨的Rdata文件中。 – user3742038