Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

r - Rmarkdown directing output file into a directory

I found a really nice trick (link) to a function of knitr, where you can save your output html into an output folder and under a different filename.

The only thing you have to head to the header is the following:

title: "analysis"
author: "Me"
date: "`r format(Sys.time(), '%d %B, %Y, %H:%M')`"
knit: (function(inputFile, encoding) { 
      rmarkdown::render(inputFile,
                        encoding=encoding, 
                        output_file=file.path(dirname(inputFile), out_dir, 'analysis.html')) })
output:
  html_document:
    number_sections: yes
    toc: yes

This works on my Mac 'sometimes' very well, but sometimes it has problems to find the out_dir variable...

I first thought about executing the chunks first, so the variable is set... But this didn't solved the problem...

I also restarted R session and this didn't helped.

The last step was closing R, saving the workspace and after reopening R and loading workspace it works like a charm again.

I could not find the original post, where somebody recommended this trick...

EXACT WORKFLOW TO REPRODUCE

open new project, name it test in a new folder
create a r markdown document
change the header to:

---
title: "Untitled"
author: "Me"
date: "`r format(Sys.time(), '%d %B, %Y, %H:%M')`"
knit: (function(inputFile, encoding) { 
      rmarkdown::render(inputFile,
                        encoding=encoding, 
                        output_file=file.path(dirname(inputFile), out_dir, 'analysis.html')) })
output:
  html_document:
    number_sections: yes
    toc: yes
---

```{r write quant output files}
out_dir <- 'test'
if(!file.exists(out_dir)) {
  dir.create(out_dir)
}
```

save the document as test.Rmd
click the knit button (html is now removed from the options of the button)
This will fail!

Close the project!
Click on save environment!

Open the Project and click knit!
Everything works.

execute rm(list=ls()) everything works afterwards again

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could try setting the out_dir variable in the function you are giving knit to render:

knit: (function(inputFile, encoding) { 
      out_dir <- 'test';
      rmarkdown::render(inputFile,
                        encoding=encoding, 
                        output_file=file.path(dirname(inputFile), out_dir, 'analysis.html')) })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...