对于典型的 R 脚本,shebang 语法可用于在其中运行代码。带文件 file.R
#!/usr/bin/env Rscript
<some R code here>
运行 ./file.R
将执行代码。但是可以用 R-markdown 来做同样的事情吗?以便使用名为
file.Rmd
的文件:#!/usr/bin/env <some command>
<some markdown>
<some R code here>
<some markdown again>
运行 ./file.Rmd
会产生 file.md
?
最佳答案
您可以将 Rmd 文件视为 Rscript。例如,假设您的 Rmd 文件如下所示
---
title: "Untitled"
author: "ekoam"
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
然后,您可以在该 Rmd 文件中添加以下代码#!/usr/bin/env Rscript
args <- commandArgs()
fname <- normalizePath(sub("--file=", "", args[grepl("--file=", args)]))
thisfile <- readLines(fname)
newfname <- paste0(tempdir(), "/", basename(fname))
writeLines(thisfile[-1:-which(thisfile == "q(\"no\")")], newfname)
rmarkdown::render(newfname, output_dir = dirname(fname))
q("no")
这里的诀窍是 q("no")
.这一行终止了 R session ,因此,在它之后写入的任何内容都将被忽略。这种效果也意味着编码的高度灵活性,因为您几乎可以在此之前编写任何有效的 R 代码 q("no")
.上面的代码只是创建了另一个临时 Rmd 文件,其内容与 q("no")
之后的内容相同。 .然后,我们rmarkdown::render
该临时文件并将输出转储到当前目录。完整的 Rmd 文件如下所示
#!/usr/bin/env Rscript
args <- commandArgs()
fname <- normalizePath(sub("--file=", "", args[grepl("--file=", args)]))
thisfile <- readLines(fname)
newfname <- paste0(tempdir(), "/", basename(fname))
writeLines(thisfile[-1:-which(thisfile == "q(\"no\")")], newfname)
rmarkdown::render(newfname, output_dir = dirname(fname))
q("no")
---
title: "Untitled"
author: "ekoam"
date: "`r Sys.Date()`"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
关于r - 是否可以创建自渲染 Rmarkdown 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64505450/