简体   繁体   English

如何通过单击可执行的 r 文件从 rmd 脚本编织 pdf?

[英]How to knit pdf from rmd script by clicking an executable r file?

Synopsis概要

I would like to produce a pdf file from an rmd script just by clicking a file / an icon so that my coworkers don't exhaust themselves by opening RStudio first.我想通过单击文件/图标从 rmd 脚本生成一个 pdf 文件,这样我的同事就不会因为先打开 RStudio 而筋疲力尽。

The question问题

When I saw this on R-bloggers, and got it working, I thought I was approaching the perfect work flow from scripting to sharing my work by letting my coworkers execute a file and get a pdf with updated numbers as a result.当我在 R-bloggers 上看到这个并让它工作时,我认为我正在接近完美的工作流程,从脚本编写到共享我的工作,让我的同事执行一个文件,结果得到一个带有更新数字的 pdf。 However, I can't get it to work with some of the functions in the knitr library.但是,我无法让它与 knitr 库中的某些功能一起使用。

Best case scenario is that this question is interesting to only a few of you out there, but here goes:最好的情况是这个问题只有少数人感兴趣,但这里是:

Below you can see a script in a file called RexecKnit.Rmd .您可以在下面看到名为RexecKnit.Rmd的文件中的脚本。 The only reason it's there is so you can test the whole procedure for yourselves if you want to.它存在的唯一原因是,如果您愿意,您可以自己测试整个过程。 By the way, I'm running RStudio Version 0.99.467 on Windows 7, 64 bit.顺便说一下,我在 64 位 Windows 7 上运行 RStudio 版本 0.99.467。

---
title: "Executable R, rmd and pdf"
header-includes: \usepackage{caption} \usepackage{fancyhdr}
output: pdf_document
fig_caption: no
---

\addtolength{\headheight}{0.5cm} 
\pagestyle{fancyplain} 
\renewcommand{\headrulewidth}{0pt}

```{r Settings, echo = FALSE, eval = TRUE, results = "hide", warning = FALSE, message = FALSE}
rm(list=ls())

pck_loaded <- (.packages())

# Packages to load
pck_toload <- c('ggplot2', 'xts', 'quantmod', 'zoo', 'PerformanceAnalytics',
            'tseries', 'mvtnorm', 'data.table', 'XLConnect', 'sqldf', 'stargazer', 'xtable', 'gridExtra', 'grid', 'TTR')

# Load packages
for(i in 1:length(pck_toload)) {
   if (!pck_toload[i] %in% pck_loaded)
    print(pck_toload[i])
    library(pck_toload[i], character.only = TRUE)
}

```

\captionsetup[table]{labelformat=empty}

```{r repex1, echo = FALSE, eval = TRUE, results = "asis", warning = FALSE, message = FALSE, fig.width = 12, fig.height = 8}

# Data table with formatted numbers and text
v1 <- c("\\colorbox{white}{0.05}" , "\\colorbox{yellow}{0.57}", "\\colorbox{red}{-0.99}")
v2 <- c("An unexpected comment", "A qurious question", "And an insightful answer")
dt1 <- data.table(v1,v2)

# Data table using xtable
print(xtable(dt1,
      caption = 'Fancy table'),
      caption.placement = 'top',
      comment = FALSE,
      sanitize.text.function = function(x) x)
```

```{r repex2, echo = FALSE, eval = TRUE, results = "asis", warning = FALSE, message = FALSE, fig.width = 12, fig.height = 8}

# Data table wiht random numbers
dt2 <- data.table(replicate(2,sample(0:100,10,rep=TRUE)))

# ggplot of random numbers
plx <- ggplot(data=dt2 ,aes(x=V1, y = V2))
plx <- plx + geom_line(color = 'blue', fill = 'grey')
plx <- plx + theme_classic()
plx <- plx + labs(title="Random numbers", x="x-axis",y="y-axis")
plot(plx)
```

I know that's a pretty lengthy script for testing purposes, but it's just to make sure that everything works when I execute the script upon double clicking this little beauty我知道这是一个很长的用于测试目的的脚本,但这只是为了确保在双击这个小美人后执行脚本时一切正常.雷克斯 which is a file called caller knitr.Rexe (like in the R-Bloggers post) containing this little piece of code:这是一个名为caller knitr.Rexe的文件(就像在 R-Bloggers 帖子中一样),其中包含以下一小段代码:

library(knitr)
library(rmarkdown)
setwd('C:/repos/r_tutorials/executable R files')
knit('RexecKnit.Rmd')
Sys.sleep(3)

And this works as expected.这按预期工作。 Upon double klicking the file, the script is run without opening R or Rstudio, and a .md file is produced in the desired folder.双击文件后,脚本将在不打开 R 或 Rstudio 的情况下运行,并在所需文件夹中生成一个 .md 文件。 And the same script works when it's stored as a .Rexe file and as a .R file.当它存储为 .Rexe 文件和 .R 文件时,相同的脚本也能工作。 But here's the problem:但问题来了:

I want to produce a pdf, and according to a tip here , replacing我想生成一个 pdf,并根据这里的提示,替换

knit('RexecKnit.Rmd')

with

rmarkdown::render("RexecKnit.Rmd")

should do the trick as long as the YAML header includes this:只要 YAML 标头包含以下内容,就应该可以解决问题:

output: pdf_document

And it does work (meaning that the pdf is created with every detail specified in the lenghty script), at least when it is run as an .R file.它确实有效(意味着 pdf 是使用 lenghty 脚本中指定的每个细节创建的),至少当它作为 .R 文件运行时。 To my disappointment, it does NOT work when it is run from a .Rexec file like this:令我失望的是,它在从 .Rexec 文件运行时不起作用,如下所示:

library(knitr)
library(rmarkdown)
setwd('C:/repos/r_tutorials/executable R files')
rmarkdown::render("RexecKnit.Rmd")
Sys.sleep(3)

Thank you for having a look at this!谢谢你看这个!

Assuming one has independently installed pandoc on Windows machine ( which turned out to be the root of the problem in this case ), she can do it in the following manner:假设一个人已经在Windows机器上独立安装了pandoc这在这种情况下是问题的根源),她可以通过以下方式进行:

First : make a .R file with the content like below首先:制作一个.R文件,内容如下

library(knitr)
library(rmarkdown)
setwd('C:/repos/r_tutorials/executable R files')
knit("RexecKnit.Rmd")

# render the generated markdown file.
render("RexecKnit.md")

Sys.sleep(3)

Second : make a .bat file第二:制作一个.bat文件

Create a .bat file, say "my_bat_file.bat", and include the text below.创建一个 .bat 文件,说“my_bat_file.bat”,并包含下面的文本。 However, the paths have to be adjusted:但是,必须调整路径:

"C:\R\R-3.2.2\bin\x64\R.exe" CMD BATCH --vanilla --slave "C:\path_to_your_file\your_file.R" "C:\path_to_your_file\your_file.Rout"

Third : Instruct Windows Task Scheduler第三:指示Windows Task Scheduler

If the data is updated frequently, one can shedule the Task Scheduler in Windows to repeatedly execute the .bat file once a week at certain time at night, so reports are there in the morning.如果数据更新频繁,可以让Windows中的Task Scheduler每周在晚上的某个时间重复执行一次.bat文件,这样早上就有报告了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM