R语言中如何查找嵌套列表内最大值对应的具体位置
R嵌套列表最大值位置查找方案
方法1:基础R递归实现(无额外依赖)
无需安装任何第三方包,可适配任意深度的数值型嵌套列表:
步骤1:构造测试列表
test <- list( a = list( c(4543, 25234, 56346, 676), c(545, 34647, 567567, 4564), c(785, 343, 95, 435) ), b = list( c(90823, 2341, 989, 5645), c(210938, 342345, 345, 78678), c(2094234, 2343, 23466, 45654) ) )
步骤2:定义查找函数
find_max_pos <- function(lst, current_path = c()) { max_val <- -Inf max_path <- c() for (i in seq_along(lst)) { elem <- lst[[i]] current_item_path <- c(current_path, i) if (is.list(elem)) { # 递归处理子列表 res <- find_max_pos(elem, current_item_path) if (res$value > max_val) { max_val <- res$value max_path <- res$path } } else if (is.numeric(elem)) { # 处理数值向量 current_max <- max(elem, na.rm = TRUE) if (current_max > max_val) { max_val <- current_max vec_pos <- which.max(elem) max_path <- c(current_item_path, vec_pos) } } } return(list(value = max_val, path = max_path)) }
步骤3:调用函数获取结果
result <- find_max_pos(test) # 输出数字索引路径 print(result$path) # 输出对应最大值验证 print(result$value)
运行后得到路径为c(2, 3, 1),对应test[[2]][[3]][[1]],最大值为2094234,和预期一致
如果需要带名称的访问路径,可以追加如下转换代码:
path_with_names <- result$path current_level <- test for (i in seq_along(path_with_names)) { level_name <- names(current_level)[path_with_names[i]] if (!is.null(level_name)) path_with_names[i] <- level_name current_level <- current_level[[path_with_names[i]]] } print(path_with_names)
输出结果为"b" "3" "1",对应test[["b"]][[3]][[1]]。
方法2:purrr包实现(适合tidyverse生态用户)
如果你已经安装了tidyverse系列的purrr包,可以用扁平化列表的方式实现:
library(purrr) # 扁平化到第二层,获取所有底层向量 flat_vecs <- flatten_depth(test, .depth = 2) # 找到最大值所在的向量位置 max_vec_idx <- which.max(map_dbl(flat_vecs, max)) # 找到向量内部的最大值位置 inner_pos <- which.max(flat_vecs[[max_vec_idx]]) # 解析为原始嵌套结构的路径 top_idx <- ceiling(max_vec_idx / length(test[[1]])) sub_idx <- max_vec_idx %% length(test[[1]]) sub_idx <- ifelse(sub_idx == 0, length(test[[1]]), sub_idx) final_path <- c(top_idx, sub_idx, inner_pos) print(final_path)
运行结果和方法1完全一致。
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

