Render quarto to HTML specifying output location lacks plots and style - r

I am trying to render a .qmd file to HTML specifying an output file. I am compiling it from a Quarto Project from RStudio on MacOS 12.6. I also have a bootstrap theme in the YAML header.
---
title: "quarto_output_experiment"
format:
html:
theme: journal
---
If I render it with Cmd + Shift + K from RStudio, the HTML document appears in the same directory as the .qmd and looks fine. However if I render it from the Quarto CLI specifying the output directory (a folder called output), the HTML can't render plots and lacks any sort of formatting and style. The command is
quarto render quarto_output_experiment.qmd --output output/report.html
Here are the results.
This is when rendered from RStudio
This is when render via Quarto CLI
What am I missing? How can I render the HTML in a different directory and have plots and proper style?
For reference, this is the document itself
---
title: "quarto_output_experiment"
format:
html:
theme: journal
---
## Quarto
Quarto enables you to weave together content and executable code into a finished document.
To learn more about Quarto see <https://quarto.org>.
```{r}
1 + 1
```
# Lorem ipsum
```{r}
library(ggplot2)
ggplot(data.frame(x = rnorm(100)), aes(x)) + geom_density()
```
UPDATE
Specifying --output-dir intead of --output produces a document with plots and style, but the question still remains if there is a way to change the name of the output HTML file? Probably not mission critical, but I'm still curious.

That is a really weird bug and it seems to be related to the path (see here. Usually, you can use quarto::render_quarto() like this,
quarto::quarto_render(input = "quarto_output_experiment.qmd", output_file = "report.html")
This works, but when you add the folder name
quarto::quarto_render(input = "quarto_output_experiment.qmd", output_file = "results/report.html")
it does not work anymore. The problem is that the folder (quarto_output_experiment_files) where the libs and images are stored, is not automatically also placed where the output-file is located.
I would file an issue here.
A possible solution for the time being would be the self-contained param that produces self-contained html files, e.g.
---
title: "quarto_output_experiment"
format:
html:
theme: journal
self-contained: true
---
then you could use file.copy to move that file in the correct folder.
Edit: The option self-contained is depreciated, use embed-resources instead! Link

Related

Img does not load in Knitr output from .Rmd to .md for Jekyll/GitHub site

I run a GitHub pages Jekyll site with the minimal mistakes theme and have spent all day yesterday trying to knit a .Rmd to .md with the proper formatting and relative file paths. I ran into a file pathing issue which is perfectly described here. I tried her workaround and it works as described.
This is where my site lives locally:
Root: ~/Developer/mkruisbrink.github.io/
Root directory is also an .Rproj
.Rmd files: ~/Developer/mkruisbrink.github.io/_reports/
ggplot2 output from .Rmd: ~/Developer/mkruisbrink.github.io/_reports/figure/
Below you will find my repex .Rmd where I'm trying to include both an image and an output from ggplot2 in the resulting .md file.
---
title: "repex"
author: "Max Kruisbrink"
date: "`r Sys.Date()`"
output:
md_document:
variant: gfm
---
{r setup, include=FALSE}
library(knitr)
library(tidyverse)
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
# define knitr paths
base.dir <- "~/Developer/mkruisbrink.github.io/"
base.url <- "/"
fig.path <- "_reports/figure/"
# set knitr parameters
opts_knit$set(base.dir = base.dir, base.url = base.url)
opts_chunk$set(fig.path = fig.path)
{r tidyverse}
knitr::include_graphics("img/icons/r-packages/thumbs/tidyverse.png")
{r ggplot-examples}
# loads ggplot
library(tidyverse)
# using the starwars dataset
data <- starwars
# plot the height distribution
ggplot(data, aes(height)) +
geom_density(aes(color = sex))
And these are the two links included in the resulting .md file
![](/img/icons/r-packages/thumbs/tidyverse.png)
![](/_reports/figure/ggplot-examples-1.png)
As you can see, the relative file paths are correct when considering Jekyll requires relative file paths from the root directory.
But... for some reason ONLY the tidyverse.png image is loaded correctly when I build my site locally. I receive this error when I load the page on localhost with the relative links:
[2022-08-12 16:06:08] ERROR "/_reports/figure/ggplot-examples-1.png" not found.
When I use the full path ![](D:/Username/Developer/mkruisbrink.github.io/_reports/figure/ggplot-examples-1.png) I don't get the error but there's no image either.
When I inspect the local page in devtools next to VSC I fail to see where the error is. The link appears correct to me?
The file is there! I'm at a loss. Anyone able to shine light on my case? I'm much obliged.
Live edits
When I try to PreviewHTML my knitted repex .md file locally with relative file paths, it loads no images at all. When I add the full paths both images are loaded.
When I push repex to GH, the image loads in the repo itself
When I visit the live blogpost, it is not loading again.
Anyone any ideas? Halp
for some reason, the whole _reports/figure/ folder wasn't recognized properly. When I changed the relative path for the .Rmd report figures to img/rmd/ using the same method, the images loaded correctly.

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 can i see output of .rmd in github?

I am practicing data analysis using R programming. I want my files to be on github. I am unable to figure out why github is not showing the output of .rmd files.
Here is the link to the file in my github repository Data Analysis Practice
I want the output including plots to be shown on github.
Instead of:
output: html_document
make it:
output: rmarkdown::github_document
(assuming you have the latest rmarkdown installed which you should if you're using RStudio — which I suspect you are — and keep it updated or update packages regularly).
It will create Exploring_one_variable.md and render the images as files.
When you browse to that markdown file, the images will render.
An alternative is to use:
output:
html_document:
keep_md: true
and it will render to both Exploring_one_variable.md and Exploring_one_variable.html so you'll have the best of both worlds without the local github-esque preview that the former provides.
You can get fancier and put something like the following as the first code section in the Rmd:
```{r, echo = FALSE}
knitr::opts_chunk$set(
fig.path = "README_figs/README-"
)
```
which will put the figures in a directory of your choosing.
You can see this in action here as the README.md was generated with knitr from the README.Rmd in the same directory.
There is now output: github_document

Knitr & Rmarkdown docx tables

When using knitr and rmarkdown together to create a word document you can use an existing document to style the output.
For example in my yaml header:
output:
word_document:
reference_docx: style.docx
fig_caption: TRUE
within this style i have created a default table style - the goal here is to have the kable table output in the correct style.
When I knit the word document and use the style.docx the tables are not stylized according to the table.
Using the style inspector has not been helpful so far, unsure if the default table style is the incorrect style to modify.
Example Code:
```{r kable}
n <- 100
x <- rnorm(n)
y <- 2*x + rnorm(n)
out <- lm(y ~ x)
library(knitr)
kable(summary(out)$coef, digits=2, caption = "Test Captions")
```
I do not have a stylized document I can upload for testing unfortunately.
TL;DR: Want to stylise table output from rmarkdown and knitr automatically (via kable)
Update: So far I have found that changing the 'compact' style in the docx will alter the text contents of the table automatically - but this does not address the overall table styling such as cell colour and alignment.
Update 2: After more research and creation of styles I found that knitr seems to have no problem accessing paragraph styles. However table styles are not under that style category and don't seem to apply in my personal testing.
Update 3: Dabbled with the ReporteRs package - whilst it was able to produce the tables as a desired the syntax required to do so is laborious. Much rather the style be automatically applied.
Update 4: You cannot change TableNormal style, nor does setting a Table Normal style work. The XML approach is not what we are looking for. I have a VBA macro that will do the trick, just want to remove that process if possible.
This is essentially a combination of the answer that recommends TableNormal, this post on rmarkdown.rstudio.com and my own experiments to show how to use a TableNormal style to customize tables like those generated by kable:
RMD:
---
output:
word_document
---
```{r}
knitr::kable(cars)
```
Click "Knit Word" in RStudio. → The document opens in Word, without any custom styles yet.
In that document (not in a new document), add the required styles. This article explains the basics. Key is not to apply direct styles but to modify the styles. See this article on support.office.com on Style basics in Word.
Specifically, to style a table you need to add a table style. My version of Word is non-English, but according to the article linked above table styles are available via "the Design tab, on the Table Tools contextual tab".
Choose TableNormal as style name and define the desired styles. In my experiments most styles worked, however some did not. (Adding a color to the first column and making the first row bold was no problem; highlighting every second row was ignored.) The last screenshot in this answer illustrates this step.
Save the document, e.g. as styles.docx.
Modify the header in the RMD file to use the reference DOCX (see here; don't screw up the indentation – took me 10 minutes find this mistake):
---
output:
word_document:
reference_docx: styles.docx
---
Knit to DOCX again – the style should now be applied.
Following the steps I described above yields this output:
And here a screenshot of the table style dialog used to define TableNormal. Unfortunately it is in German, but maybe someone can provide an English version of it:
As this does not seem to work for most users (anyone but me …), I suggest we test this systematically. Essentially, there are 4 steps that can go wrong:
Wrong RMD (unlikely).
Differences in the initially generated DOCX.
Differences in how the TableNormal style is saved in the DOCX.
Differences in how the reference DOCX is used to format the final DOCX.
I therefore suggest using the same minimal RMD posted above (full code on pastebin) to find out where the results start do differ:
My initially generated DOCX.
The same document with TableNormal added: reference.docx
The final document.
The three files are generated on the following system: Windows 7 / R 3.3.0 / RStudio 0.99.896 / pandoc 1.15.2 / Office 2010.
I get the same results on a system with Windows 7 / R 3.2.4 / RStudio 0.99.484 / pandoc 1.13.1 / Office 2010.
I suppose the most likely culprits are the pandoc and the Office versions. Unfortunately, I cannot test other configurations at the moment. Now it would be interesting to see the following: For users where it does not work, what happens …
… if you start from my initial.docx?
If that does not work, what if you use my reference.docx as reference document?
If nothing works, are there eye-catching differences in the generated XML files (inside the DOCX container)? Please share your files and exact version information.
With a number of users running these tests it should be possible to find out what is causing the problems.
This was actually a known issue. Fortunately, it was solved in v2.0 or later releases of pandoc.
And I have tested the newer version, and found that there is a newly-added hidden style called "Table". Following #CL.'s suggestions to change "Table" style in reference.docx will be okay now.
In addition, look at this entry of pandoc's v2.0 release notes:
Use Table rather than Table Normal for table style (#3275). Table Normal is the default table style and can’t be modified.
As of 2021, I could not get any of the other suggested answers to work.
However, I did discover the {officedown} package, which, amongst other things, supports the styling of tables in .docx documents. You can install {officedown} with remotes::install_github("davidgohel/officedown")
To use {officedown} to render .Rmd to .docx you must replace
output:
word_document
in your document header with
output:
officedown::rdocx_document
In addition to this the {officedown} package must be loaded in your .Rmd.
As with the word_document output format, {officedown} allows us to use styles and settings from template documents, again with the reference_docx parameter.
With a reference document styles.docx, a minimal example .Rmd may look like:
---
date: "2038-01-19"
author: "The Reasonabilists"
title: "The end of time as we know it"
output:
officedown::rdocx_document:
reference_docx: styles.docx
---
```{r setup, include = FALSE}
# Don't forget about me: I'm important!
library("officedown")
```
{officedown} allows us to go one step further and specify the name of the table style to use in the document's front matter. This table style could be a custom style we created in styles.docx, or it could be one of Word's in-built styles you prefer.
Let's say we created a style My Table:
We could tell {officedown} to use this table style in our front matter as:
output:
officedown::rdocx_document:
reference_docx: styles.docx
tables:
style: My Table
Putting this altogether, knitting the minimal .Rmd:
---
date: "2038-01-19"
author: "The Reasonabilists"
title: "The end of time as we know it"
output:
officedown::rdocx_document:
reference_docx: styles.docx
tables:
style: My Table
---
```{r setup, include = FALSE}
# Don't forget about me: I'm important!
library(officedown)
```
```{r}
head(mtcars)
```
Resulting in a .docx document which looks like:
TableNormal doesn't work for me too.
On my Dutch version of Word 2016 (Office 365), I found out that I could markup tables with the style Compact.
Input (refdoc.docx contains the Compact style):
---
title: "Titel"
subtitle: "Ondertitel"
author: "`r Sys.getenv('USERNAME')`"
output:
word_document:
toc: true
toc_depth: 2
fig_width: 6.5
fig_height: 3.5
fig_caption: true
reference_docx: "refdoc.docx"
---
And RMarkdown:
# Methoden {#methoden}
```{r}
kable(cars)
```
Output:
You need to have a reference_docx: style.docx which has "Table" style in it. (see #Liang Zhang's explanation and links above).
Create a basis reference document using pandoc (source). In command line (or cmd.exe on Windows) run:
pandoc -o custom-reference.docx --print-default-data-file reference.docx
In this newly created reference.docx file, find the table created (a basic 1 row table with a caption).
While the table is selected, click "Table Design" and find "Modify Table Style":
Modify the style of the table as you wish and use this reference document in your RMD document (see the first answer by #CL.).
Using this reference document, you can also change the table and figure caption styles.
I was able to get my word output to use a default table style that I defined in a reference .docx.
Instead of 'TableNormal', the table style it defaulted to was 'Table'.
I discovered this by knitting an rmarkdown with a kable.
---
date: "December 1, 2017"
output:
word_document:
reference_docx: Template.docx
---
`r knitr::kable(source)`
Then I took a look at that generated document's XML to see what style it had defaulted to.
require(XML)
docx.file <- "generated_doc.docx"
## unzip the docx converted by Pandoc
system(paste("unzip", docx.file, "-d temp_dir"))
document.xml <- "temp_dir/word/document.xml"
doc <- xmlParse(document.xml)
tblStyle <- getNodeSet(xmlRoot(doc), "//w:tblStyle")
tblStyle
I defined the 'Table' style to put some color and borders in the reference docx. This works for one standard table style throughout the document, I haven't found a way to use different styles throughout.
This stayed true even after I opened the reference doc and edited it.

Referencing master file with rmarkdown (knitr)

I have a parent which includes a child file, and I'd like to compile the parent file, when I press Cmd+shift+k (I'm using rstudio). I know in latex you can reference a master file by writing a line of code at the top of your child file. I was wondering if you could do something similar with rmarkdown?
In R Markdown it works like this:
---
title: "parent"
output: pdf_document
---
This is the title page
```{r child='child1.Rmd'}
```
```{r child='child2.Rmd'}
```
The child .Rmd files are in the same folder in this example.
You do not need to specify a YAML header in the child .Rmd's
The knitr /demo/child/ page has an overview on how to do this.
If that's not informative enough, you can check out the knitr section of a thesis template repo's README.
Finally, you can see the parent-child model in action over in https://github.com/stevenpollack/masters_thesis/blob/master/masters_thesis.Rnw. A stripped down version of that link would be:
\documentclass[masters]{ucbthesis}
\begin{document}
<<abstract, child='abstract.Rnw'>>=
#
<<introduction, child='introduction.Rnw'>>=
#
<<adaboostToBoost, child='boosting_methodology.Rnw'>>=
#
<<boostrImplementation, child='boostr_implementation.Rnw'>>=
#
<<discussion, child='summary_and_future_work.Rnw'>>=
#
\end{document}

Resources