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

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))

Related

Export R script without output to PDF/Word

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")
}

static image of targets workflow, programatically

I'm trying to embed a static image of a targets workflow in an rmarkdown document. I tried to do this by using tar_mermaid, defining a target that writes the workflow in mermaid format mm <- tar_mermaid(); writeLines(mm, "target_mermaid.js") but the help for tar_mermaid says
You can visualize the graph by copying
the text into a public online mermaid.js editor or a mermaid GitHub code chunk
I am looking for a programmatic way to either (1) embed the Javascript output in an (R)markdown file, or (2) render it (as SVG, PNG, whatever).
I thought as a shortcut that I could cut-and-paste into a markdown code chunk delimited by ```mermaid, or use cat(readLines("target_mermaid.js"), sep = "\n") in a chunk with results = "asis" but I guess that only works in Github markdown (I'm using Pandoc to render to HTML) ... ?
The visNetwork package has a visSave() function which can save to HTML (not quite what I wanted but better than what I've managed so far), and a visExport() function (which saves to PNG etc. but only by clicking in a web browser). Furthermore, targets wraps the visNetwork functions in a way that is (so far) hard for me to unravel (i.e., it doesn't return a visNetwork object, but automatically returns a widget ...)
For the time being I can go to https://mermaid.live, paste in the mermaid code, and export the PNG manually but I really want to do it programmatically (i.e. as part of my workflow, without manual steps involved).
I am not quite sure about the answer. But I have an idea. And I will delete if it is not adequate:
If you want execute mermaid code to get for example an html output then you could do this with quarto. I am not sure if this is possible with rmarkdown:
See https://quarto.org/docs/authoring/diagrams.htmlS
---
title: "Untitled"
format: html
editor: visual
---
## Quarto
Quarto enables you to weave together content and executable code into a finished document. To learn more about Quarto see <https://quarto.org>.
## Running Code
```{mermaid}
flowchart LR
A[Hard edge] --> B(Round edge)
B --> C{Decision}
C --> D[Result one]
C --> E[Result two]
```
output:
#landau's suggestion to look here almost works, if I'm willing to use Quarto instead of Rmarkdown (GH Markdown is not an option). The cat() trick was the main thing I was missing. The .qmd file below gets most of the way there but has the following (cosmetic) issues:
I don't know how to suppress the tidyverse startup messages, because targets is running the visualization code in a separate R instance that the user has (AFAIK) little control of;
the default size of the graph is ugly.
Any further advice would be welcome ...
---
title: "targets/quarto/mermaid example"
---
```{r}
suppressPackageStartupMessages(library("tidyverse"))
library("targets")
```
```{r, results = "asis", echo = FALSE}
cat(c("```{mermaid}", tar_mermaid(), "```"), sep = "\n")
```
Beginning of document:
Zooming out:

How to replicate Knit HTML in a command line?

I know this question is similar to this one. But I couldn't get a solution there so posting it here again.
I want to get the exact same output as I get by clicking "Knit HTML" but via a command. I tryied using knit2html but it messes with the formatting and does not include the title, kable does not work etc.
Example:
This is my test.Rmd file,
---
title: "test"
output: html_document
---
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}
library(knitr,quietly=T)
kable(summary(cars))
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Output:
Knit HTML
knit2html
The documentation tells us:
If you are not using RStudio then you simply need to call the rmarkdown::render function, for example:
rmarkdown::render("input.Rmd")
Note that in the case using the “Knit” button in RStudio the basic mechanism is the same (RStudio calls the rmarkdown::render function under the hood).
In essence, rmarkdown::render does a lot more setup than knitr::knit2html, although I don’t have an exhaustive list of all differences.
The most flexible way of rendering the output is, at any rate, to supply your own stylesheet to format the output according to your wishes.
Please note that you need to set up Pandoc manually to work with rmarkdown::render on the command line.
That said, here are two remarks that would improve the knitr::knit2hmtl output, and that are superior to using rmarkdown::render in my opinion:
To include the title, use a Markdown title tag, not a YAML tag:
# My title
To format tables, don’t use the raw kable function. In fact, this is also true when using rmarkdown::render: the alignment of the table cells is completely off. Rmarkdown apparently uses centering as the default alignment but this option is almost never correct. Instead, you should left-align text and (generally) right-align numbers. As of this writing, Knitr cannot do this automatically (as far as I know) but it’s fairly easy to include a filter to do this for you:
```{r echo=FALSE}
library(pander)
# Use this option if you don’t want tables to be split
panderOptions('table.split.table', Inf)
# Auto-adjust the table column alignment depending on data type.
alignment = function (...) UseMethod('alignment')
alignment.default = function (...) 'left'
alignment.integer = function (...) 'right'
alignment.numeric = function (...) 'right'
# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
if (is.data.frame(object) ||
is.matrix(object)) {
# Replicate pander’s behaviour concerning row names
rn = rownames(object)
justify = c(if (is.null(rn) || length(rn) == 0 ||
(rn == 1 : nrow(object))) NULL else 'left',
sapply(object, alignment))
pander(object, style = 'rmarkdown', justify = justify)
}
else if (isS4(object))
show(object)
else
print(object)
})
```

GitHub displays all code chunks from README.rmd (despite include=FALSE)

I am currently writing a documentation for an R package hosted on GitHub. I use knitr along with R Markdown to write the README file. Hitting the 'Knit HTML' button in RStudio produces an HTML like I would expect it.
However, pushing README.rmd to GitHub results in what you see in the lower page section when following the above link. For example, the topmost code chunk is declared as follows in the README.rmd file:
```{r global_options, include = FALSE}
library(knitr)
options(width = 120)
opts_chunk$set(fig.width = 12, fig.height = 8, fig.path = 'Figs/',
include = TRUE, warning = FALSE, message = FALSE)
```
However, the include = FALSE statement in the first line of code is simply ignored in this case, and the piece of code that was supposed to be hidden is displayed on the referring GitHub page. In addition, results (e.g. from plot(), head()) are not visualized although opts_chunk$set(..., include = TRUE).
Did anyone encounter a similar problem and can me help me get my README document displayed correct, i.e. in the way RStudio would handle it, on GitHub?
The readme file you are trying to publish on github should be a plain markdown document i.e., a .md file and not the raw .rmd. So first you knit the .rmd with knitr (within R) as follows:
knit(input="readme.rmd", output = "readme.md") #see ?knit for more options
That will evaluate the global and chunk options specified in the source .rmd and produce a .md that's formatted accordingly and which github can render readily.
For more information on using an .Rmd to generate the .md see the Readme.Rmd section of http://r-pkgs.had.co.nz/release.html
You can also have devtools set up this automatically for your package using devtools::use_readme_rmd().

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).

Resources