我一直在按照此說明在 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")
輸出串列的結構將如下所示(列印在控制臺中)。在此注意向量在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"
當然,該函式必須是遞回的才能應用于任何不同的情況。
uj5u.com熱心網友回復:
這是一種可能的方法,僅使用基礎 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)
$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"
uj5u.com熱心網友回復:
使用外部包,這可以rrapply()在rrapply-package 中非常有效地完成:
rrapply::rrapply(lst, f = function(x, .xparents) .xparents)
#> $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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376498.html
上一篇:基于向量復制一行(特定列)
下一篇:從C#中的串列中洗掉串列項的屬性
