获取 R 中嵌套列表最深层的名称

Mig*_*rez 5 recursion r

我一直在按照此说明使用 R 中的嵌套列表和递归函数。现在我只错过了设计一个自己的函数的一个部分,即获取一个向量,其各自的名称从最高层到最深层排序。

输入列表为:

lst <- list(
    title = "References and Plant Communities in 'SWEA-Dataveg'",
    author = "Miguel Alvarez",
    date = "Dezember 28, 2019",
    "header-includes" = c(
        "- \\usepackage[utf8]{inputenc}",
        "- \\usepackage[T1]{fontenc}", "- \\usepackage{bibentry}",
        "- \\nobibliography{sweareferences.bib}"),
    output = list(pdf_document=list(citation_package="natbib")),
    "biblio-style" = "unsrtnat",
    bibliography = "sweareferences.bib",
    papersize = "a4")
Run Code Online (Sandbox Code Playgroud)

输出列表的结构将如下所示(在控制台中打印)。请注意 处的向量lst$output$pdf_document$citation_package

$title
[1] "title"

$author
[1] "author"

$date
[1] "date"

$`header-includes`
[1] "header-includes"

$output
$output$pdf_document
$output$pdf_document$citation_package
[1] "output"
[2] "pdf_document"
[3] "citation_package"

$`biblio-style`
[1] "biblio-style"

$bibliography
[1] "bibliography"

$papersize
[1] "papersize"
Run Code Online (Sandbox Code Playgroud)

当然,该函数必须是递归的才能应用于任何不同的情况。

Mik*_*gan 3

这是一种可能的方法,仅使用基 R。以下函数f将递归列表的每个终端节点(或“叶子”)替换x为指向该节点的名称序列。它将未命名列表视为所有名称都等于 的命名列表"",这是一个有用的概括。

f <- function(x, s = NULL) {
  if (!is.list(x)) {
    return(s)
  }
  nms <- names(x)
  if (is.null(nms)) {
    nms <- character(length(x))
  }
  Map(f, x = x, s = Map(c, list(s), nms))
}

f(lst)
Run Code Online (Sandbox Code Playgroud)
$title
[1] "title"

$author
[1] "author"

$date
[1] "date"

$`header-includes`
[1] "header-includes"

$output
$output$pdf_document
$output$pdf_document$citation_package
[1] "output"           "pdf_document"     "citation_package"



$`biblio-style`
[1] "biblio-style"

$bibliography
[1] "bibliography"

$papersize
[1] "papersize"
Run Code Online (Sandbox Code Playgroud)