米科·马蒂拉帮助我找到了一种动态时间戳文件的方法,使用working代码如下:
---
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)
})
---
然而,我还想指定从内部的输出位置knitr
代码,基于projectmanager
and project
。如果该文件夹尚不存在,则应创建该文件夹。
这可以按如下方式完成:link。我尝试将这些解决方案结合起来。
我尝试过以几种不同的方式做到这一点,但不知何故我无法让它发挥作用。
所需的输出位置:
.../projectname/project")
我尝试使用setwd
以及使用file.path
:
---
title: "Untitled"
author: "Jane Doe"
date: "`r Sys.Date()`"
output: word_document
projectmanager: "Earth Worm Jim"
project: "getstuffdone"
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))
# Tom: Specify the main directory in which to store all folders
main_directory <- "Z:/Coding/R_scripts/Markdown/RMarkdown_out/"
# Check current working directory
print(getwd())
# print(metadata)
# Dynamically create a full path for the new file based on projectmanager and project
out_dir <- with(metadata, paste0(main_directory, projectmanager, "/", project, "/"))
print(out_dir)
# Here I tried to set the working directory to the dynamically created wd
setwd(out_dir)
print(getwd())
# Build output file name based on rendered metadata
output_name <- with(metadata, paste(title, date, initials))
print(output_name)
output_dir = file.path(dirname(output_name), out_dir)
print(output_dir)
# path_ext() returns the last extension (if any) for a path
output_ext <- fs::path_ext(output_file_temp)
print(output_ext)
# replaces the extension with a new extension path_ext_set(path, ext)
output_file <- fs::path_ext_set(output_name, output_ext)
print(output_file)
fs::file_move(output_file_temp, output_file)
message("Output file: ", output_file)
})
---