【问题标题】:Generate table of contents from the yaml header title of a list of R Markdown files从 R Markdown 文件列表的 yaml 标题生成目录
【发布时间】:2016-09-26 13:10:19
【问题描述】:

有没有办法通过 R 的方式从 R Markdown 文件列表中生成 yaml 头标题列表?假设你有两个文件

A.Rmd

---
title: Titel of first file
---

B.Rmd

---
title: Titel of second file
---

那么列表应该是这样的

File |Title
-----|--------------------
A.Rmd|Titel of first file
B.Rmd|Titel of second file

这个列表是否也可以生成为 R Markdown 文件 - 最好带有指向原始文件的链接?

【问题讨论】:

    标签: r yaml r-markdown


    【解决方案1】:

    这是一个小而方便的函数,它为您提供标题和文件名:

    read_RMD_titles <- function(files){
    
      names_list <- lapply(1:length(files), function(x){
    
       title <- readLines(files[x])[2] 
    
        return(c(files[x], title))
    
      })
    
      return(unlist(names_list))  
    
    }
    
    read_RMD_titles(files = c("A.Rmd", "B.Rmd"))
    # [1] "A.Rmd" "title: \"Untitled\""                      
    # [3] "B.Rmd" "title: \"Untitled\""  
    

    您现在可以根据自己的需要修改此方法。这应该是一个起点。

    【讨论】:

    • 这是一个起点:包裹到下一行的标题怎么样?
    • 感谢这个答案我修改了函数read_RMD_titles
    • 很高兴,您找到了满足您需求的解决方案!
    • 刚刚找到这个rmarkdown:::parse_yaml_front_matter(readLines(file))$title
    【解决方案2】:

    感谢the answer from J_F我修改了他/她的功能如下:

    read_RMD_titles <- function(files){  
      names_list <- lapply(files, function(file) {
        lines = readLines(file)
        headerIdx = grep("^---\\s*$",lines)
        title = ""
        if (2 <= length(headerIdx)) {
          titleIdx = grep("^title:",lines[c(headerIdx[1]:headerIdx[2])])
          if (1 <= length(titleIdx)) {
            title = trimws(sub("^title:\\s*", "", lines[headerIdx[1] + titleIdx[1] - 1]))
            for (i in c(headerIdx[1] + titleIdx[1]:headerIdx[2])) {
              if (0 < regexpr("^\\s{2,}", lines[i])) {
                title = paste(title, trimws(lines[i]))
              } else {
                break
              }
            }
          }
        }
        return (c(file,title))
      })
    
      return(unlist(names_list))
    }
    

    如果你喜欢这个,请为他/她的回答投票。

    ...或者感谢answer to another question:

    rmarkdown:::parse_yaml_front_matter(readLines(file))$title
    

    可能会被使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 2013-03-23
      • 2017-09-10
      相关资源
      最近更新 更多