如何提取R列表的所有名称,直到嵌套最深的子列表?[副本]

e0bqpujr  于 2023-10-13  发布在  其他
关注(0)|答案(2)|浏览(107)

此问题已在此处有答案

Get names at deepest level of a nested list in R(2个答案)
昨天关门了。
这篇文章是编辑并提交审查23小时前.
如何从R列表中提取所有名称,挖掘到嵌套最深的子列表名称,如下图所示?复制这个示例列表的代码在本文的底部,代表了我正在使用的一个更大的动态列表。在下面的代码中,我试图从中提取嵌套子列表名称的列表对象名为list_tmp。如果可能的话,我宁愿在base R中这样做,以避免“包膨胀”,或者如果base R很繁重,则使用超标准的包之一,如dupiter或tidyverse。

生成此示例列表的代码:

# Create the matrix for columns Col_A and Col_B
mat_tmp <- matrix(0, nrow = 2, ncol = 2)
colnames(mat_tmp) <- c("Col_A","Col_B")

# Build list
list_tmp1 <- list(
  Top = list(
    Middle_One = list(
      A = mat_tmp,
      B = mat_tmp,
      Total = mat_tmp
    ),
    Middle_Two = list(
      A = mat_tmp,
      Total = mat_tmp
    )
  )
)

list_tmp2 <- list(
  Top = list(
    Total = mat_tmp
  )
)

list_tmp3 <- list(
  Top = list(
    Other = matrix(0, nrow = 2, ncol = 1)
  )
)

list_tmp <- c(list_tmp1,list_tmp2, list_tmp3)
gmxoilav

gmxoilav1#

要获得所需的名称,可以使用递归函数

node_names <- function(x, prefix="") {
  if (is.list(x)) {
    unname(unlist(mapply(node_names, x, paste0(prefix, "$", names(x)))))
  } else {
    prefix
  }
}
node_names(list_tmp)
# [1] "$Top$Middle_One$A"     "$Top$Middle_One$B"     "$Top$Middle_One$Total" "$Top$Middle_Two$A"    
# [5] "$Top$Middle_Two$Total" "$Top$Total"            "$Top$Other"
qmelpv7a

qmelpv7a2#

又快又脏:

full_names <- list()
get_names <- function(x, ancestors = character(0)) {
  if (!is.list(x)) {
    full_names <<- c(full_names, paste(ancestors, collapse = "$"))
  } else {
    for (i in seq_along(x)) get_names(x[[i]], ancestors = c(ancestors, names(x)[i]))
  }
}
get_names(list_tmp)
unlist(full_names)

# [1] "Top$Middle_One$A"     "Top$Middle_One$B"     "Top$Middle_One$Total" "Top$Middle_Two$A"     "Top$Middle_Two$Total"
# [6] "Top$Total"            "Top$Other"

相关问题