Export R script without output to PDF/Word - r

Is it possible to export the R script to a PDF and/or Word document without the outputs (i.e. without whatever the console prints; plots, graphs etc.)? I know about the r markdown package but as far as I know, it exports the script only with outputs.

rmarkdown is very flexible, you don't have to include output. If you set the option eval = FALSE none of the code will be evaluated, so no outputs will be generated.
See here for a detailed list of options available at the code-chunk level.

To follow up on #GregorThomas's answer: if you simply add R code block-formatting around all of your code with eval=FALSE specified and save it with an .rmd extension, you can then click "Knit to PDF" in RStudio (which will automatically add a minimal header). I think you could probably also do rmarkdown::render("myfile.rmd", output_format = "pdf_document"). If you wanted you could set up a little script to do the minimal editing and rendering automatically ...
```{r eval = FALSE}
x <- 2+3
print("hello")
```
Something like (untested!)
printme <- function(file) {
tt <- tempfile(fileext = ".Rmd")
writeLines(c("```{r eval=FALSE}",
readLines(file),
"```"),
tt)
rmarkdown::render(tt, output_format = "pdf_document",
output_file = "out.pdf")
}

Related

Change option settings with knit:pagedown::chrome_print in Rmarkdown YAML

I have created a large R Markdown document with many child docs using RStudio to produce output in both HTML and PDF.
I added this simple line to the YAML parameters of the document and it does exactly what I need. The entire doc is rendered and saved as both html and pdf output. Formatting of complex tables is preserved nicely.
knit: pagedown::chrome_print
BUT - the pdf is oversized. It simply needs to be scaled to 0.8 to be really useable. chrome_print documentation says that scale can be adjusted within the chrome_print command. I've tried this:
knit: pagedown::chrome_print(scale = 0.8)
which produces an Execution Halted error. I have tested other ways to pass parameters through the render to chrome_print, but none work.
The question is simple: Is there a way to pass parameters into the knit: pagedown::chrome_print operation?
After much experimentation, I find there is currently no way to adjust any pdf options from within R markdown YAML using knit: pagedown::chrome_print.
The workaround I've found is to use the code chunk below to render the Rmarkdown. It saves to both html and pdf formats and allows the user to assign filenames. Note that scaling does not adjust pagination nicely without CSS reset as shown. This works great, and allows full use of rmarkdown parameters and all chrome_print options.
fname = "OutputFilename"
pagedown::chrome_print(
rmarkdown::render(
input = "input.Rmd",
output_file = paste0(fname, ".html"),
output = paste0(fname, ".pdf"),
options = list(scale = 0.7, preferCSSPageSize = FALSE))

run an R Markdown (check.Rmd ) and an R knitr (test.Rnw ) file together

I have the following problem; There are 2 big documents, one written in R Markdown (check.Rmd ) and the other in R knitr (test.Rnw ). In the first doc we have a code like the following:
\section{Organisations Test}
\textbf{Running Organisations Checks}
<<CreateOrganisations, echo=FALSE, progress=TRUE, warning=FALSE, eval=TRUE>>=
source("OrganisationsTest.R")
OrganisationsTest(current_schema,server,user,pass)
#
and in the other as follows:
2. check the downwards shock
```{r chunk_Int_Sh_p2, echo=FALSE}
unique(param.int.shock.tab[SHOCKTYPE=="SHOCK_DOWN"&PERIODEND<21|PERIODEND==90, list( Maturity=PERIODEND, Shock_value=100*SHOCKVALUE)])
```
Now the question: how can I combine both so that I have just one script which runs and compile both one after each other. Just for clarification, I mean without any changes in both documents how can I have just one script which applyes to the first doc knit PDF to create pdf and to the other one CompilePDF ?
I suppose in Linux one can write a shell script but what a bout using RStudio in windowes?
I am really grateful for every hint I am a little bit helpless!
Addendum: In principle it is as follows: we have 2 files if you would compile a knitr file you would use bottom in RStudio, and for a Markdown file one may use bottom in RStudio, BUT we want to put both together and klick on one bottom. How is it possible?
The RStudio buttons "Compile PDF" (for RNW documents) and "Knit PDF" (for RMD documents) are convenient, but in cases like this one it is important to understand what they do in order to reproduce the same or similar behavior.
Summing the question up, it asks for a way to convert two files (a RMD and a RNW document) to PDF, preferably using a button like the two buttons mentioned above.
Unfortunately, (up to my knowledge) it is not possible to add any user-defined buttons to the RStudio GUI. But it is straightforward to write an R script that compiles both documents.
In the following I assume two files:
first.Rmd:
This is a RMD file.
```{r, echo=FALSE}
plot(1)
```
second.Rnw:
\documentclass{article}
\begin{document}
This is a RNW file.
<<>>=
plot(1)
#
\end{document}
To compile first.Rmd to PDF, we need the following (see How to convert R Markdown to PDF?):
library(knitr)
library(rmarkdown)
knit(input = "first.Rmd")
render(input = "first.md", output_format = "pdf_document")
The knit call generates first.md from first.Rmd, execting the R code in the chunks. render converts the resulting markdown file to PDF. [Note the addendum at the bottom!]
To compile first.Rnw to PDF, we can simply use knit2pdf:
knit2pdf("second.Rnw")
Copying both snippets into one R script and clicking "Source" is as close as possible to a "one-button-solution".
However, note that the snippets do something very similar to the "Compile / knit PDF" button, but it is not identical. The "Compile" buttons start a new R session while the solution above uses the current session.
Before executing the snippets make sure to use the correct working directory.
Both knit and knit2pdf by default use envir = parent.frame(). That means R code in chunks is executed in the calling enironment (see What is the difference between parent.frame() and parent.env() in R). This can be a useful feature, for example to "pass" variables to chunks, but it is important to know about it. Otherwise a document might compile just fine in one session (where certain variables exist in the calling environment) but cannot be compiled in another session (that is missing these variables). Therefore, this feature is a little bit dangerous in terms of reproducibility. As a solution, envir = new.env(parent = as.environment(2)) could be used; see knitr inherits variables from a user's environment, even with envir = new.env() for more details on that topic.
I just realized to following about render:
If the input requires knitting then knit is called prior to pandoc.
(Source: ?render)
Therefore, knit(input = "first.Rmd"); render(input = "first.md", output_format = "pdf_document") can be simplified to render(input = "first.Rmd", output_format = "pdf_document"). The envir issues of knit from above apply to render as well.

knitr: Knitting separate Rnw documents within an Rmd document

I have a master R markdown document (Rmd) within which I would like to knit several separate Rnw documents (NO child documents) in one of the chunks. However, when I call knit on the Rnw document, the contained R code chunks do not seem to be processed, resulting in an error when trying to run texi2pdf on them.
Illustration of the situation:
Inside master.Rmd:
```{r my_chunk, echo=FALSE, message=FALSE, results='asis'}
... some code ...
knit("sub.**Rnw**", output = ..., quiet = TRUE)
tools::texi2pdf(tex_file)
... some code ...
```
Is there some additional configuration required to make this scenario work?
There are a few reasons you can't directly do what you are trying to do (calling knit from within a knit environment)...
Knitr patterns are already set.
[ In this case markdown patterns, so you'd need to set the patterns to 'rnw' patterns. ]
Parsing the chunks (after setting the correct patterns) will add chunk labels to the existing concordance, so unless all chunks are unique you will get a duplicate chunk label error.
[ This is why knit_child exists. ]
The output target and other options are already set, so you either need a completely new knitr environment or to save, modify, restore all pertinent options.
That being said, it seems like completely expected behavior.
Something along the lines of
library(knitr)
files <- list.files( pattern = "*.Rnw", path = ".")
files
## [1] "test_extB.Rnw" "test_ext.Rnw"
for( f in files ) {
system( paste0("R -e \"knitr::knit2pdf('", f, "')\"") )
}
list.files( pattern="*.pdf", path=".")
## [1] "test_extB.pdf" "test_ext.pdf"
or calling Rscript in a loop should do the trick (based on the info provided), which is essentially what #kohske was expressing in the comments.

Dynamic LaTeX references in R comment with knitr

I had ask a similar question to this with respect to Sweave (
Dynamic references to figures in a R comment within Sweave document
) and would like to see if anyone as a similar answer when using knitr.
The goal is to have the following code chunk
<<"example", fig.cap = "some figure", highlight = FALSE>>=
# the following code generated Figure \ref{fig:example}
plot(1:10, 1:10)
#
have be displayed in the resulting .pdf as
# the following code generated Figure 1.1
plot(1:10, 1:10)
So far I have found that by setting highlight = FALSE the R code is placed into a verbatim environment in the resulting .tex file. If the environment could be alltt instead of verbatim then we'd have the desired output. Is it possible to have the non-highlighted code chunks be placed in alltt environments via a knitr option?
I have added an example 072-latex-reference.Rnw in the knitr-examples repository. The basic idea is to restore the escaped \ref{} (which should have been \textbackslash{}ref\{\} in the default output).

How to source R Markdown file like `source('myfile.r')`?

I often have a main R Markdown file or knitr LaTeX file where I source some other R file (e.g., for data processing). However, I was thinking that in some instances it would be beneficial to have these sourced files be their own reproducible documents (e.g., an R Markdown file that not only includes commands for data processing but also produces a reproducible document that explains the data processing decisions).
Thus, I would like to have a command like source('myfile.rmd') in my main R Markdown file. that would extract and source all the R code inside the R code chunks of myfile.rmd. Of course, this gives rise to an error.
The following command works:
```{r message=FALSE, results='hide'}
knit('myfile.rmd', tangle=TRUE)
source('myfile.R')
```
where results='hide' could be omitted if the output was desired. I.e., knitr outputs the R code from myfile.rmd into myfile.R.
However, it doesn't seem perfect:
it results in the creation of an extra file
it needs to appear in its own code chunk if control over the display is required.
It's not as elegant as simple source(...).
Thus my question:
Is there a more elegant way of sourcing the R code of an R Markdown file?
It seems you are looking for a one-liner. How about putting this in your .Rprofile?
ksource <- function(x, ...) {
library(knitr)
source(purl(x, output = tempfile()), ...)
}
However, I do not understand why you want to source() the code in the Rmd file itself. I mean knit() will run all the code in this document, and if you extract the code and run it in a chunk, all the code will be run twice when you knit() this document (you run yourself inside yourself). The two tasks should be separate.
If you really want to run all the code, RStudio has made this fairly easy: Ctrl + Shift + R. It basically calls purl() and source() behind the scene.
Factor the common code out into a separate R file, and then source that R file into each Rmd file you want it in.
so for example let's say I have two reports I need to make, Flu Outbreaks and Guns vs Butter Analysis. Naturally I'd create two Rmd documents and be done with it.
Now suppose boss comes along and wants to see the variations of Flu Outbreaks versus Butter prices (controlling for 9mm ammo).
Copying and pasting the code to analyze the reports into the new report is a bad idea for code reuse, etc.
I want it to look nice.
My solution was to factor the project into these files:
Flu.Rmd
flu_data_import.R
Guns_N_Butter.Rmd
guns_data_import.R
butter_data_import.R
within each Rmd file I'd have something like:
```{r include=FALSE}
source('flu_data_import.R')
```
The problem here is that we lose reproducibility. My solution to that is to create a common child document to include into each Rmd file. So at the end of every Rmd file I create, I add this:
```{r autodoc, child='autodoc.Rmd', eval=TRUE}
```
And, of course, autodoc.Rmd:
Source Data & Code
----------------------------
<div id="accordion-start"></div>
```{r sourcedata, echo=FALSE, results='asis', warnings=FALSE}
if(!exists(autodoc.skip.df)) {
autodoc.skip.df <- list()
}
#Generate the following table:
for (i in ls(.GlobalEnv)) {
if(!i %in% autodoc.skip.df) {
itm <- tryCatch(get(i), error=function(e) NA )
if(typeof(itm)=="list") {
if(is.data.frame(itm)) {
cat(sprintf("### %s\n", i))
print(xtable(itm), type="html", include.rownames=FALSE, html.table.attributes=sprintf("class='exportable' id='%s'", i))
}
}
}
}
```
### Source Code
```{r allsource, echo=FALSE, results='asis', warning=FALSE, cache=FALSE}
fns <- unique(c(compact(llply(.data=llply(.data=ls(all.names=TRUE), .fun=function(x) {a<-get(x); c(normalizePath(getSrcDirectory(a)),getSrcFilename(a))}), .fun=function(x) { if(length(x)>0) { x } } )), llply(names(sourced), function(x) c(normalizePath(dirname(x)), basename(x)))))
for (itm in fns) {
cat(sprintf("#### %s\n", itm[2]))
cat("\n```{r eval=FALSE}\n")
cat(paste(tryCatch(readLines(file.path(itm[1], itm[2])), error=function(e) sprintf("Could not read source file named %s", file.path(itm[1], itm[2]))), sep="\n", collapse="\n"))
cat("\n```\n")
}
```
<div id="accordion-stop"></div>
<script type="text/javascript">
```{r jqueryinclude, echo=FALSE, results='asis', warning=FALSE}
cat(readLines(url("http://code.jquery.com/jquery-1.9.1.min.js")), sep="\n")
```
</script>
<script type="text/javascript">
```{r tablesorterinclude, echo=FALSE, results='asis', warning=FALSE}
cat(readLines(url("http://tablesorter.com/__jquery.tablesorter.js")), sep="\n")
```
</script>
<script type="text/javascript">
```{r jqueryuiinclude, echo=FALSE, results='asis', warning=FALSE}
cat(readLines(url("http://code.jquery.com/ui/1.10.2/jquery-ui.min.js")), sep="\n")
```
</script>
<script type="text/javascript">
```{r table2csvinclude, echo=FALSE, results='asis', warning=FALSE}
cat(readLines(file.path(jspath, "table2csv.js")), sep="\n")
```
</script>
<script type="text/javascript">
$(document).ready(function() {
$('tr').has('th').wrap('<thead></thead>');
$('table').each(function() { $('thead', this).prependTo(this); } );
$('table').addClass('tablesorter');$('table').tablesorter();});
//need to put this before the accordion stuff because the panels being hidden makes table2csv return null data
$('table.exportable').each(function() {$(this).after('<a download="' + $(this).attr('id') + '.csv" href="data:application/csv;charset=utf-8,'+encodeURIComponent($(this).table2CSV({delivery:'value'}))+'">Download '+$(this).attr('id')+'</a>')});
$('#accordion-start').nextUntil('#accordion-stop').wrapAll("<div id='accordion'></div>");
$('#accordion > h3').each(function() { $(this).nextUntil('h3').wrapAll("<div>"); });
$( '#accordion' ).accordion({ heightStyle: "content", collapsible: true, active: false });
</script>
N.B., this is designed for the Rmd -> html workflow. This will be an ugly mess if you go with latex or anything else. This Rmd document looks through the global environment for all the source()'ed files and includes their source at the end of your document. It includes jquery ui, tablesorter, and sets the document up to use an accordion style to show/hide sourced files. It's a work in progress, but feel free to adapt it to your own uses.
Not a one-liner, I know. Hope it gives you some ideas at least :)
Try the purl function from knitr:
source(knitr::purl("myfile.rmd", quiet=TRUE))
Probably one should start thinking different. My issue is the following:
Write every code you normally would have had in a .Rmd chunk in a .R file.
And for the Rmd document you use to knit i.e. an html, you only have left
```{R Chunkname, Chunkoptions}
source(file.R)
```
This way you'll probably create a bunch of .R files and you lose the advantage of processing all the code "chunk after chunk" using ctrl+alt+n (or +c, but normally this does not work).
But, I read the book about reproducible research by Mr. Gandrud and realized, that he definitely uses knitr and .Rmd files solely for creating html files. The Main Analysis itself is an .R file.
I think .Rmd documents rapidly grow too large if you start doing your whole analysis inside.
If you are just after the code I think something along these lines should work:
Read the markdown/R file with readLines
Use grep to find the code chunks, searching for lines that start with <<< for example
Take subset of the object that contains the original lines to get only the code
Dump this to a temporary file using writeLines
Source this file into your R session
Wrapping this in a function should give you what you need.
The following hack worked fine for me:
library(readr)
library(stringr)
source_rmd <- function(file_path) {
stopifnot(is.character(file_path) && length(file_path) == 1)
.tmpfile <- tempfile(fileext = ".R")
.con <- file(.tmpfile)
on.exit(close(.con))
full_rmd <- read_file(file_path)
codes <- str_match_all(string = full_rmd, pattern = "```(?s)\\{r[^{}]*\\}\\s*\\n(.*?)```")
stopifnot(length(codes) == 1 && ncol(codes[[1]]) == 2)
codes <- paste(codes[[1]][, 2], collapse = "\n")
writeLines(codes, .con)
flush(.con)
cat(sprintf("R code extracted to tempfile: %s\nSourcing tempfile...", .tmpfile))
source(.tmpfile)
}
I use the following custom function
source_rmd <- function(rmd_file){
knitr::knit(rmd_file, output = tempfile())
}
source_rmd("munge_script.Rmd")
I would recommend keeping the main analysis and calculation code in .R file and importing the chunks as needed in .Rmd file. I have explained the process here.
sys.source("./your_script_file_name.R", envir = knitr::knit_global())
put this command before calling the functions contained in the your_script_file_name.R.
the "./" adding before your_script_file_name.R to show the direction to your file if you already created a Project.
You can see this link for more detail: https://bookdown.org/yihui/rmarkdown-cookbook/source-script.html
I use this one-liner:
```{r optional_chunklabel_for_yourfile_rmd, child = 'yourfile.Rmd'}
```
See:
My .Rmd file becomes very lengthy. Is that possible split it and source() it's smaller portions from main .Rmd?
I would say there is not a more elegant way of sourcing an Rmarkdown file. The ethos of Rmd being that the report is reproducible and at best will be self contained. However, adding to the OP's original solution, the below method avoids the permanent creation of the intermediate file on disk. It also makes some extra effort to ensure chunk output does not appear in the renderred document:
knit_loc <- tempfile(fileext = ".R")
knitr::knit("myfile.rmd",
output = knit_loc,
quiet = TRUE,
tangle = TRUE)
invisible(capture.output(source(knit_loc, verbose = FALSE)))
I would also add that if the child markdown dependencies are external to your R environment (eg write a file to disk, download some external resource, interact with a Web api etc), then instead of knit() I would opt for rmarkdown::render() instead:
rmarkdown::render("myfile.rmd")
this worked for me
source("myfile.r", echo = TRUE, keep.source = TRUE)
The answer by #qed is by far the best. Kevin Keena built the function proposed by #Paul Hiemstra, and this can help you to convert your .Rmd into an .R file to then source the code into another .R file, where knitr::purl would not be available.

Resources