I am writing a report using r markdown. However, after this report is produced I would like to continue to analyse the data without having to open up a new editor window.
I was wondering if there is a simple command I could use to express the end of the document?
Thanks.
It appears that you are not necessarily interested in ending your markdown document but in hiding your results. The code below will enable you to continue the analysis in the same window and to exclude it from appearing in the core document when compiled.
```{r results='hide', message=FALSE, warning=FALSE}
# Stuff that you want to do
```
For a more detailed explanation, you may want to have a look at the Chunk Options in the knitr documentation.
Related
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:
I'm having a problem with assigning LaTeX environments within an RMarkdown for-loop code-chunk.
In short, I've written an R Markdown document and a series of R-scripts to automatically generate PDF reports at the end of a long data analysis pipeline. The main section of the report can have a variable number of sections that I'm generating using a for-loop, with each section containing a \subsection heading, a datatable and plot generated by ggplot. Some of these sections will be very long (spanning several pages) and some will be very short (~1/4 of a page).
At the moment I'm just inserting a \pagebreak at the end of each for-loop iteration, but that leaves a lot of wasted space with the shorter sections, so I'm trying to "group" each section (i.e. the heading, table and chart) so that there can be several per page, but they will break to a new page if the whole section won't fit.
I've tried using a figure or minipage environment, but for some reason those commands are printed as literal text when the plot is included; these work as expected with the heading and data table, but aren't returned properly in the presence of the image.
I've also tried to create a LaTeX samepage environment around the whole subsection (although not sure this will behave correctly with multi-page sections?) and then it appears that the Markdown generated for the plot is not interpreted correctly somewhere along the way (Pandoc?) when it's within that environment and throws an error when compiling the TeX due to the raw Markdown ![]... image tag.
Finally, I've also tried implementing \pagebreak[x] and \nopagebreak[y] hints at various points in the subsection but can't seem get these to be produce the desired page breaking behaviour.
I've generated an MWE that reproduces my issues below.
I'd be really grateful for any suggestions on how to get around this, or better ways of approaching "grouping" of elements that are generated in a dynamic fashion like this?
---
title: "Untitled"
author: "I don't know what I'm doing"
date: "26/07/2020"
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, dev = "cairo_pdf")
```
```{r cars, results='asis'}
for (i in 1:5){
cat("\\begin{figure}")
cat(paste0("\\subsection{This is subsection ",i,"}"))
cat("\\Huge Here's some bulk text that would represent a data table... kasvfkwsvg fiauwe grfiwgiu iudaldbau iausbd ouasbou asdbva asdbaisd i iuahihai hiuh iaiuhqijdblab ihlibljkb liuglugu h uhi uhi uhqw iuh qoijhoijoijoi qwegru wqe grouw egq\\newline")
plot(mtcars$wt,mtcars[,i])
cat("\\end{figure}")
}
```
Edit to add: interestingly these figure and minipage environments seems to work as expected when executing the same example in an .Rnw using knitr... so does that narrow it down to an issue with Pandoc? Again, any help much appreciated!
What happens is that the raw TeX commands are not treated as TeX when going through Markdown. You can fix that by explicitly marking the relevant snippets as LaTeX:
for (i in 1:5){
cat("`\\begin{figure}`{=latex}")
cat(paste0("\\subsection{This is subsection ",i,"}"))
cat("\\Huge Here's some bulk text that would represent a data table... kasvfkwsvg fiauwe grfiwgiu iudaldbau iausbd ouasbou asdbva asdbaisd i iuahihai hiuh iaiuhqijdblab ihlibljkb liuglugu h uhi uhi uhqw iuh qoijhoijoijoi qwegru wqe grouw egq\\newline")
plot(mtcars$wt,mtcars[,i])
cat("`\\end{figure}`{=latex}")
}
See the generic raw attribute section in the pandoc manual for details.
I'm creating a tutorial that involves telling the reader what to put into a file we'll call utils.R. The user would get the tutorial as an HTML file. Throughout the tutorial utils.R changes and the Rmd document uses the code in utils.R as it exists at that stage of the tutorial. During the rendering, I'd like for the code chunks to use source("utils.R") as it exists at that stage of the tutorial. I'm looking for a way to either...
1. Write the contents of a code chunk to a file. For example...
```{r utils_1}
summary(cars)
median(cars$speed)
```
Is there a way to write the code in utils_1 to a file?
2. Create a nicely formatted code chunk from a text string (I know how to write that to a file). For example...
z <- "summary(cars)\nmedian(cars$speed)"
write(z, "utils.R")
Will generate utils.R, but is there a way to turn z into a properly formatted code chunk.
I could create multiple versions of utils.R and use echo=F to hide that I'm loading that behind the scenes, but that seems like a pain.
Not sure if this is what are you looking for but you can use child option to generate them from another file. I use it for automated reports as it helps to keep the main Rmd a bit simpler
```{r child=utils.R}
```
I often place the child code in the YAML though, and call it (matter of tastes I guess...):
---
params:
utils: "utils.R"
---
```{r child=params$utils}
```
Is there any way possible to include code for different languages in Rmarkdown documents while authoring books using bookdown package? I have looked at the knitr option like engine with possible values like python, awk/gawk and the executable path can be set using engine.path.
```{r, engine='python'}
print "Will this code chunk be hidden?"
```
However, I would like to just insert code (eg: git) in the Rmarkdown document without executing it.
For example, like including in the markdown documents
```git
git init
```
If you don't want the code to be executed, you can embed it like:
```
code not executed
```
You can also have code highlighting in specific languages:
```css
my_css{}
```
For your git command, this is execution from terminal, so you can highlight it with:
```sh
git init
```
I am using knit()and markdownToHTML() to automatically generate reports.
The issue is that I am not outputting plots when using these commands. However, when I use RStudio's Knit HTML button, the plots get generated. When I then use my own knit/markdown function, it suddenly outputs the plot. When I switch to another document and knit that one, the old plot appears.
Example:
```{r figA, result='asis', echo=TRUE, dpi=300, out.width="600px",
fig=TRUE, fig.align='center', fig.path="figure/"}
plot(1:10)
```
Using commands:
knit(rmd, md, quiet=TRUE)
markdownToHTML(md, html, stylesheet=style)
So I guess there are 2 questions, depending on how you want to approach it:
What magic is going on in Rstudio's Knit HTML?
How can I produce/include without depending on RStudio's Knit HTML button?
The only issue I see here is that this doesn't work when you have the chunk options {...} spanning two lines. If it's all on one line, it works fine. Am I missing something?
See how this is not allowed under knitr in the documentation:
Chunk options must be written in one line; no line breaks are allowed inside chunk options;
RStudio must handle linebreaks in a non-standard way.
This is really embarrassing, I really thought I read the documentation carefully:
include: (TRUE; logical) whether to include the chunk output in the
final output document; if include=FALSE, nothing will be written into
the output document, but the code is still evaluated and plot files
are generated if there are any plots in the chunk, so you can manually
insert figures; note this is the only chunk option that is not cached,
i.e., changing it will not invalidate the cache
Simply adding {..., include=TRUE} did the trick. I would say it would be a pretty sensible default though.