如何通过坐标索引为R嵌套列表的指定元素设置名称?
解决方案:通过索引坐标为嵌套列表元素命名
你可以自定义一个函数来实现通过坐标索引为嵌套列表元素命名的需求,核心是定位到目标元素所在的父列表,再为对应位置设置名称。
自定义实现函数
pluck_set_name <- function(lst, indices, name) { # 处理顶层元素命名的情况 if (length(indices) == 1) { names(lst)[indices] <- name return(lst) } # 提取父列表的索引(去掉最后一位) parent_indices <- indices[-length(indices)] # 定位到目标元素所在的父列表 parent_list <- purrr::pluck(lst, !!!parent_indices) # 为父列表的对应位置设置名称 names(parent_list)[indices[length(indices)]] <- name # 将修改后的父列表放回原列表 purrr::assign_in(lst, parent_indices, parent_list) }
使用示例
# 初始未命名嵌套列表 lst <- list(1, list(2, 3)) str(lst) #> List of 2 #> $ : num 1 #> $ :List of 2 #> ..$ : num 2 #> ..$ : num 3 # 给索引c(2,1)的元素命名为"C" lst <- pluck_set_name(lst, c(2,1), "C") str(lst) #> List of 2 #> $ : num 1 #> $ :List of 2 #> ..$ C: num 2 #> ..$ : num 3 # 批量完成所有命名 lst <- pluck_set_name(lst, c(2,2), "D") lst <- pluck_set_name(lst, 1, "A") lst <- pluck_set_name(lst, 2, "B") str(lst) #> List of 2 #> $ A: num 1 #> $ B:List of 2 #> ..$ C: num 2 #> ..$ D: num 3
核心逻辑说明
- 列表元素的名称属于其父列表的属性,而非元素自身,所以需要先定位到目标元素的父列表
- 用
purrr::pluck()获取父列表,修改对应位置的名称后,再通过purrr::assign_in()将父列表替换回原列表
内容的提问来源于stack exchange,提问作者mpettis
相关产品推荐
相关产品推荐

