I have many markdown files, each with many codeblocks, see an example below. (They were converted to this format via pandoc from other file types)
I would like to knit these in as Rmd files. Right now, the codeblocks have no decorators. When I knit the file below, there is no code syntax styling/coloring. I do not want to evaluate the code, I just want to print them out, hence: knitr::opts_chunk$set(warning=FALSE, message=FALSE, cache=FALSE).
Suppose all the code are MATLAB code, is there something I can add like: knitr::opts_chunk$set(code=MATLAB), so that they would all get MATLAB code styling/coloring?
My code chunks are actually all MATLAB code, so MATLAB stlying/coloring would be more helpful, but any code styling would be great to make the code chunks in outputted HTML/PDF etc easier to read.
---
title: matlab code in blocks
output: html_document
---
# RMD file with Markdown Code Blocks
```{r global_options, include = FALSE}
knitr::opts_chunk$set(warning=FALSE, message=FALSE, cache=FALSE)
```
## Example 1
Here is a code block A
fl_fig_wdt = 3;
fl_fig_hgt = 2.65;
figure('PaperPosition', [0 0 fl_fig_wdt fl_fig_hgt], 'Renderer', 'Painters');
x = rand([10,1]);
y = rand([10,1]);
scatter(x, y, 'filled');
grid on;
grid minor;
## Section 2
Here is a code block B
fl_fig_wdt = 5;
fl_fig_hgt = 5.65;
figure('PaperPosition', [0 0 fl_fig_wdt fl_fig_hgt], 'Renderer', 'Painters');
x = rand([20,1]);
y = rand([20,1]);
scatter(x, y, 'filled');
grid on;
grid minor;
End of file.
If you need a general solution, you need to use a Pandoc Lua filter (I'm not able to write one for you; see the Github issue that you cross-posted). If you only need HTML output, you may use JavaScript to add a class name to the code blocks, e.g., add this js code chunk to the end of your document:
```{js, echo=FALSE}
document.querySelectorAll('pre').forEach(function(el) {
// the class name is the language name
// (I'm using R here, although it's not the right name)
if (!el.className) el.className = 'r';
});
```
The output looks like this:
Related
I have an rmd chunk of r code with a loop. The structure of the code is like this:
```{r echo=FALSE, results="asis", out.width="100%"}
## out.width="100%"
## fig.width=12
## fig.height=(6+2*ceiling(6/4))
section_number <- 3
i = 1 ## for testing
while (i <= length(target_var_list)) {
target_var <- target_var_list[i]
data_segments <- data_segments(wrangled_devices, target_var)
# Code
exposure_chart_data <- monkeyr::get_exposure_chart_data(wrangled_obs, wrangled_devices, target_var)
exposure_plot <- monkeyr::get_exposure_plot(exposure_chart_data, target_var)
# knitr::opts_chunk$set(fig.height=(6+2*ceiling(data_segments/4)))
print(exposure_plot)
# print(exposure_plot, fig.height=(12+2*ceiling(data_segments/4)))
section_number <- section_number + 1
cat("\n\n\n")
i <- i + 1
}
```
I have commented out a few attempts I made to control the width and height of the plot. And I have commented out 2 attempts I made to control the knitr behaviour on a per plot basis.
The problem is that I can't find a reliable way to control the plot size that accommodates different lengths of the target_var_length.
It is possible to control the height at chunk level, but that is then fixed, and won't respond to each element in the loop. Here are some viz. What I would like is for the actual bar to be the same size in every case. So the case with 3 values would be 75% as wide as the 4. And the case with 7 would look be 2 rows, so twice the height of the 4. Do you see what I mean...
After quite a few hours of messing around with different approaches, here are some insights and an answer.
knitr::opts_chunk$set
I expected this to take effect on execution and change the chunk options for whatever elements follow. To change the plot height based on the number of rows / column in a facetted plot, I tried this:
knitr::opts_chunk$set(fig.height=(6+2*ceiling(data_segments/4)))
However it has no effect. The documentation bears this out. This actually sets the default chunk settings for subsequent chunks, and has no effect whatsoever on the current chunk. I encountered another function:
knitr::opts_current$set(fig.height=(6+2*ceiling(data_segments/4)))
The documentation as much as warns you off using this. And I found that it didn't achieve the expected results either in any case.
Blind Hope
I considered the possibility that I was overthinking this and left it up to blind hope by removing all efforts to control the height. Sometimes things just work out you know! ... They didn't.
Using an rmd child chunk
This is the approach that I finally got to work. It's a slightly horrible hack. My first effort was to create a separate rmd file for each plot:
```{r echo=FALSE, results="asis", out.width="100%", fig.height=(6+2*ceiling(data_segments/4))}
print(myPlot)
```
But that meant creating lots of new rmd plots. I have a major problem with how messy that would get. So I cleaned it up by using a single rmd file for any plot and lumped the code to call it into a fucntion.
resize_plot <- function(resizePlot, resizeHeight) {
resizePlot <- resizePlot
resizeHeight <- resizeHeight
res <- knitr::knit_child('resizePlot.rmd', quiet = TRUE)
cat(res, sep = '\n')
}
Now to insert a custom height plot I just call my new function:
resize_plot(exposure_plot, 3.25*ceiling(data_segments/4))
And the single rmd file just looks like this:
```{r echo=FALSE, results="asis", out.width="100%", fig.height=resizeHeight}
print(resizePlot)
```
And bingo - it looks perfect!
I am currently writing my thesis in RMarkdown using the template Oxforddown (which is ultimately based on bookdown). I have been reading the documentation but I confess I am lost. I am trying to create a table that contains an overview of the experimental conditions and items I used in my empirical study, so it is not data that I can load into R and then use the kable function on. However, I do not understand how I could generate such a table. Generating RMarkdown tables outside code chunks seems to work, but then the captions and referencing are very different than the rest of the captions used so far, which I usually set up within code chunks. Example below:
{r pilot-short7, echo=FALSE, fig.scap="Pilot 2: ....", out.width="65%", message=FALSE, fig.pos='H', fig.align = 'center'}
When I am trying to include RMarkdown tables inside a code chunks, things go wrong. What would my options be?
Any help would be very much appreciated!
I prepared a markdown template for you.
Here I made a table with flextable library.
But you can use another, which you like, f.e.: kableExtra, gt etc.
As you can see, you should put \label{tab:caption} and after refer in the text by \ref{tab:caption}.
---
title: "Hello World"
header-includes:
- \usepackage{caption}
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, include = FALSE}
library(flextable)
library(dplyr)
table2 <- flextable(mtcars[1:5, 1:6])
```
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:
\begin{table}[hbtp]
\captionof{table}{Text of the caption.}
\label{tab:caption}
`r table2`
\end{table}
Table \ref{tab:caption} is the baddest table in the World
In R markdown when using Beamer slides if you try to plot you need to specify the plot sizes (unlike in the reports) so that the plots fit on a page. This can often result in the plots appearing to be squashed together, as apposed to just a smaller version of the plot.
Is there some method to change the default slide size to alleviate this problem?
I have tried
header-includes:
- \usepackage[papersize={25.6cm,19.2cm}]{geometry}
in the yaml header, and I get the error
! LaTeX Error: Missing \begin{document}.
Using R Markdown I shouldn't need to use this though.
A reproducible example is shown below
---
title: "Plots look bad"
author: "Beavis"
date: "`r format(Sys.time(), '%d/%m/%Y')`"
output: beamer_presentation
header-includes:
- \usepackage{float}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
knitr::opts_chunk$set(results = 'hide')
knitr::opts_chunk$set(warning = FALSE)
knitr::opts_chunk$set(cache=TRUE)
knitr::opts_chunk$set(fig.height=3.5)
```
# Introduction
```{r}
pca <- prcomp(iris[,1:4])
biplot(pca)
```
Here, you if you run this the second slide looks like this As you can see the plot is rubbish. What is the best way to avoid this problem?
The biplot function uses par(pty = "s") to force a square plot, so it's not going to fill a rectangular slide. You can make it look better by asking the fig.height to be bigger, but then it will overflow the bottom of the slide. To prevent this, you can set both fig.height to a large number, and out.height (which will be a LaTeX measurement) to something that will fit on a slide. For example, using this chunk
```{r fig.height=10, out.height="0.8\\textheight"}
pca <- prcomp(iris[,1:4])
biplot(pca)
```
I see this output:
I'd recommend a smaller fig.height, but your preference may be different.
Both fig.height and out.height could be specified using knitr::opts_chunk$set as defaults for all slides if you want.
You could also specify out.width="\\textwidth" for a really ugly stretched plot that fills the slide, but I wouldn't recommend it.
Due to different journal requirements, I need to frequently change certain text styles within Rmarkdown from one kind to another. For instance, here is an example Rmarkdown document.
---
title: "Changing format of Rmarkdown"
author: "Paul Hargarten"
date: "5/9/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an $\mathcal{R}$ Markdown document. Markdown is a simple formatting syntax for authoring **HTML**, **PDF**, and **MS Word* documents. For more details on using $\mathcal{R}$ Markdown see <http://rmarkdown.rstudio.com>. $\matcal{R}$ is based on $\mathcal{S}$.
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. Calculate a `summary` as follows:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example: `r plot(pressure)`.
Without searching for the exact phrase, suppose that I would like to find and replace the following items:
1. Change items in bold ** ... ** to italics _ ... _.
2. Change items that look like $\mathcal{ ... }$ to bold ** ... **.
3. Change special font `...`, except those that start with r, to \code{ ... }.
4. Add dollar signs to `r ... ` => $`r ... `$.
Is this possible to use regex to make these formatting style changes in
Rmarkdown? Thanks!
This is something that LaTeX is good at, but it will be harder with Markdown.
If you were entirely in LaTeX, you could define your own macros based on the uses for that markup. For example,
\newcommand{\booktitle}[1]{\textbf #1}
used for book titles as \booktitle{The Book}. If you wanted to switch book titles to italic, you'd just change that definition.
Doing this in R Markdown is possible, but you wouldn't be able to mark book titles using **. You could do it (you can embed LaTeX in R Markdown), but it's ugly. For example,
---
title: Using LaTeX
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
\newcommand{\booktitle}[1]{\textbf{#1}}
This is \booktitle{The Book}.
Once you're doing this, you might as well switch to Sweave-like *.Rnw format, or all the way to LaTeX.
I am trying to render the syntax for chunks of code in RMarkdown to a pdf. The final output should look like
```{r}
#some code
```
Rather than just
#some code
The best options to answer this can be found on the RStudio website. See the article on getting verbatim R chunks into rmarkdown http://rmarkdown.rstudio.com/articles_verbatim.html
My preferred solution is to add an inline R code at the end of the first line to make the chunk appear correctly in the output like so:
```{r eval=TRUE}` r ''`
seq(1, 10)
```
Which produces
```{r eval=TRUE}
seq(1:10)
```
Rather than
## [1] 1 2 3 4 5 6 7 8 9 10
Another way to do the same thing is treat the code chunk as a string (I don't usually use the -> operator but in this case I think this improves readability):
```{r comment = ""}
"{r eval=TRUE}
seq(1, 10)
" -> my_code_string
cat("```", my_code_string, "```", sep = "")
```
Which outputs:
```{r eval=TRUE}
seq(1, 10)
```
This question is also a possible duplicate of How to embed and escape R Markdown code in a R Markdown document