2

Is there a way to generate a list of the yaml header titles from a list of R Markdown files with the means of R? Suppose you have two files

A.Rmd

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

B.Rmd

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

Then the list should look like

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

Could this list be generated as R Markdown file too - preferable with links to the original files?

Claude
  • 1,724
  • 3
  • 17
  • 46

2 Answers2

2

Here is a small and handy function, which gives you the title and the filename:

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\""  

You can modify this approach to your own needs now. This should be a starting point.

J_F
  • 9,956
  • 2
  • 31
  • 55
0

Thanks to the answer from J_F I modified his/her function as follows:

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))
}

If you like this please vote on his/her answer.

... or thanks to the answer to another question:

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

might by used.

Community
  • 1
  • 1
Claude
  • 1,724
  • 3
  • 17
  • 46