【问题标题】:Convert list object to unordered list in markdown在降价中将列表对象转换为无序列表
【发布时间】:2018-09-14 15:57:35
【问题描述】:

我有一个包含字符向量的列表。我想在 RMarkdown 文档中创建一个无序列表。我试图通过遍历列表并将输出粘贴到降价列表中来实现这一点。在knitr 中打印结果'asis'。这是一个玩具示例。

test <- list(x = c('a', 'b', 'c'), y = c('d', 'e'))

我想创建一个这样的无序列表:

- x
    - a
    - b
    - c
- y
    - d
    - e

我已经尝试使用 for 循环与 catpaste0 结合使用来执行此操作。

cols <- names(test)

for (columns in names(test)) {
  cat(paste0("- ", names(test[columns]), '\n', '    ', 
             "- ", test[[cols[columns]]], '\n')) 
}

哪些输出”

- x
    - 
- y
    - 

如果能获得我上面描述的所需无序列表,我将不胜感激。

【问题讨论】:

    标签: r list markdown r-markdown knitr


    【解决方案1】:

    这是一个不需要循环的解决方案。 List 和 yaml 文档很相似,所以你可以把它转换成 yaml(稍微修改一下)和cat

    test <- list(A = c("a", "b", "c"), B = c("d", "e"), C = 1:5)
    cat(gsub("^!omap\n|:", "", yaml::as.yaml(test, omap = TRUE)))
    

    解释:

    • 使用来自yaml packageas.yaml 函数将列表转换为有序yaml。
    • 使用gsub 删除omap 标头。
    • cat 结果。


    你也可以把它放在一个自定义函数中,这样你就不会泛滥代码:

    catList <- function(inputList) {
        cat(gsub("^!omap\n|:", "", yaml::as.yaml(inputList, omap = TRUE)))
    }
    catList(test)
    

    【讨论】:

      【解决方案2】:

      试试这个:

      ---
      title: "SO Answer"
      author: "duckmayr"
      date: "September 14, 2018"
      output: html_document
      ---
      
      ```{r unordered_list, echo=FALSE, results='asis'}
      test <- list(x = c('a', 'b', 'c'), y = c('d', 'e'))
      
      for (name in names(test)) {
          cat("-", name, '\n', paste('   -', test[[name]], '\n'))
      }
      ```
      

      对我来说,这会产生:

      您之前尝试的方式有两个问题:

      1. 您应该使用 test[[columns]] 而不是 test[[cols[columns]]] 进行子集化,并且
      2. 即使您修复了该问题,您仍可以看到 paste 给您带来了一些问题:
      for (columns in names(test)) {
         cat(paste0("- ", names(test[columns]), '\n', '    ', 
                    "- ", test[[columns]], '\n')) 
      }
      
      
      - x
          - a
       - x
          - b
       - x
          - c
      - y
          - d
       - y
          - e
      

      【讨论】:

        猜你喜欢
        • 2013-12-02
        • 1970-01-01
        • 1970-01-01
        • 2011-01-01
        • 2021-06-28
        • 2013-08-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多