在自定义 R-markdown 函数中动态命名输出文件

Tom*_*Tom 3 r knitr r-markdown

我在这里找到了下面的功能。它工作得很好,但我想'analysis.docx'使用文档标题、作者和当前日期动态命名输出文件。

title: thetitle
author: myinititals
date: "`r Sys.Date()`"
knit: (function(inputFile, encoding) { 
          out_dir <- 'test';
          rmarkdown::render(inputFile,
                            encoding=encoding, 
                            output_file=file.path(dirname(inputFile), out_dir, 'analysis.docx')) })
Run Code Online (Sandbox Code Playgroud)

在这种情况下如何使'analysis.docx'动态化?

我在这里找到了更多信息,但不是我想要的答案。

Mik*_*ila 7

如果您要使用的字段不包含 R 表达式,您可以使用yaml_front_matter()提取它们的值并使用它们来构造输出文件的名称:

---
title: "Untitled"
author: "Jane Doe"
date: "18/02/2022"
output: word_document
knit: >
  (function(input_file, encoding) {
    metadata <- rmarkdown::yaml_front_matter(input_file)
    output_file <- with(metadata, paste(title, "by", author))
    rmarkdown::render(input = input_file, output_file = output_file)
  })
---

204 No Content
Run Code Online (Sandbox Code Playgroud)

如果您的字段确实包含 R 表达式,那么这会变得更加复杂。您可以应用相同的原理,但现在不是从 RMarkdown 文件中获取前面的内容,而是从渲染过程中生成的中间 Markdown 文件中获取它。然后重命名结果。

这可能看起来像这样:

---
title: "Untitled"
author: "Jane Doe"
date: "`r Sys.Date()`"
output: word_document
knit: >
  (function(input_file, encoding) {
    # Render, keeping intermediate files for extracting front matter
    md_dir <- tempdir()
    output_file_temp <- rmarkdown::render(
      input = input_file,
      output_file = tempfile(),
      intermediates_dir = md_dir,
      clean = FALSE
    )
    
    # Get the rendered front matter from the intermediate Markdown file
    md_file <- fs::path_ext_set(fs::path_file(input_file), ".knit.md")
    metadata <- rmarkdown::yaml_front_matter(fs::path(md_dir, md_file))
    
    # Build the output file name based on rendered metadata
    output_name <- with(metadata, paste(title, "by", author, "on", date))

    # Add the file extension and move to the working directory
    output_ext <- fs::path_ext(output_file_temp)
    output_file <- fs::path_ext_set(output_name, output_ext)
    fs::file_move(output_file_temp, output_file)

    message("Output moved to: ", output_file)
  })
---

204 No Content
Run Code Online (Sandbox Code Playgroud)