bap*_*ste 213 yaml r knitr r-markdown
我想知道是否有一个技巧可以将当前日期放在.rmd要处理的文档的YAML前端knitr和rmarkdown包中.我以前在我的维基页面顶部有以下行,
_baptiste, `r format(Sys.time(), "%d %B, %Y")`_
Run Code Online (Sandbox Code Playgroud)
它将在html输出中转换为2014年5月3日的baptiste.现在,我想利用由提供的高级pandoc包装器rmarkdown,但在YAML头中使用r代码似乎不起作用:
---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
date: `r format(Sys.time(), "%d %B, %Y")`
author: baptiste
---
Error in yaml::yaml.load(front_matter) :
Scanner error: while scanning for the next token at line 6, column 7
found character that cannot start any token at line 6, column 7
Calls: <Anonymous> ... output_format_from_yaml_front_matter ->
parse_yaml_front_matter -> <Anonymous> -> .Call
Run Code Online (Sandbox Code Playgroud)
任何解决方法?
Yih*_*Xie 325
这有点棘手,但你只需要date通过引用内联R表达式使字段在YAML中有效,例如
date: "`r format(Sys.time(), '%d %B, %Y')`"
Run Code Online (Sandbox Code Playgroud)
然后解析错误将消失,日期将在降价输出中生成,因此Pandoc可以使用来自的值Sys.time().
Joh*_*n M 67
刚刚关注@Yihui.奇怪的是,我发现:
'`r format(Sys.Date(), "%B %d, %Y")`'
Run Code Online (Sandbox Code Playgroud)
效果比:
"`r format(Sys.Date(), '%B %d, %Y')`"
Run Code Online (Sandbox Code Playgroud)
对于后者,RStudio选择'在HTML和PDF输出之间切换时更改外部引号,从而破坏代码.
Sab*_*DeM 15
或者只引用双引号,反之亦然,这很有效.
---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
date: '`r format(Sys.time(), "%d %B, %Y")`'
author: baptiste
---
Run Code Online (Sandbox Code Playgroud)
Ram*_*ath 11
一种解决方法是使用该brew包并将您的YAML前端内容编写为brew模板.
---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
date: <%= format(Sys.time(), "%d %B, %Y") %>
author: baptiste
---
Run Code Online (Sandbox Code Playgroud)
您现在可以使用一个brew_n_render函数来预处理doc brew,然后运行rmarkdown.
brew_n_render <- function(input, ...){
output_file <- gsub("\\.[R|r]md$", ".html", input)
brew::brew(input, 'temp.Rmd'); on.exit(unlink('temp.Rmd'))
rmarkdown::render('temp.Rmd', output_file = output_file)
}
Run Code Online (Sandbox Code Playgroud)
为了使用KnitHTMLRStudio中的按钮,您可以编写一个自动brew用作预处理器的自定义输出格式.使用brew预处理可确保knitr在预处理阶段保持文档中的代码块不受影响.理想情况下,rmarkdown程序包应在其API中公开元数据,并允许用户通过自定义函数运行它.
oli*_*roy 10
或者,如果您使用新格式 quarto https://quarto.org。您可以在 .qmd 文件的 yaml 标头中执行此操作。
\n\xe2\x80\x94\xe2\x80\x94-\ntitle: title of my doc\ndate: today\nformat:\n html:\n theme: default\n\xe2\x80\x94\xe2\x80\x94-\nRun Code Online (Sandbox Code Playgroud)\n对于格式化,请在此处检查格式化选项。
\n举个例子,
\ndate: 03/07/2005\ndate-format: long\nRun Code Online (Sandbox Code Playgroud)\n