Use custom pygments syntax highlighting style in rmarkdown - r-markdown

How can I use a custom pygments syntax highlighter in rmarkdown? With pygments I created a file nice.py:
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic
class niceStyle(Style):
default_style = ""
styles = {
Operator: "bold #818181",
Number: "bold #0000cf",
Generic: "#000000",
Comment: 'italic #08a542',
Keyword: 'bold #0000cf',
Name: '#f00',
Name.Function: '#0000cf',
Name.Class: 'bold #0f0',
String: '#ff7f50'
}
Now I want to use this for syntax highlighting in rmarkdown:
---
output: beamer_presentation
# highlight: nice
---
```{r}
# Comment
f <- function(x = 10, y = "abc") {
paste0(x, y)
}
f()
```
Maybe I can include this with knitr::knit_hooks$set? or is there another way?

Related

using a for loop to generate a series of plots in new powerpoint slides using quarto

I am creating a quarto powerpoint presentation and want to use a dataset to iterate over all the classes in a variable and do a plot for each class on a new slide. However, my plot doesn't seem to show up
---
title: "test_quarto_presentation"
format: pptx
editor: visual
---
## Quarto
Trying to iterate over each species and print the distributions on slides
```{r}
library(tidyverse)
```
```{r, results='asis'}
for (species in unique(iris$Species)){
cat(paste0('## ', species))
print("test")
print(iris %>%
filter(Species == "virginica") %>%
ggplot(aes(x = Petal.Length)) +
geom_histogram())}
```
Here is an option by producing the plots beforehand using purrr based on this discussion:
---
title: "test_quarto_presentation"
format: pptx
---
```{r, include=FALSE}
library(tidyverse)
spec_name <- unique(iris$Species)
make_hist <- function(spec) {
iris |>
filter(Species == spec) |>
ggplot(aes(x = Petal.Length)) +
geom_histogram()
}
list_hist <- map(spec_name, make_hist)
df <- tibble(spec = spec_name, plots = list_hist)
```
```{r}
#| output: asis
res <- pmap_chr(df, \(spec, plots) {
knitr::knit_child(text = c(
"## `r spec`",
"```{r}",
"#| echo: false",
"plots",
"```",
""), envir = environment(), quiet = TRUE)
})
cat(res, sep = '\n')
```
Output:

Knitr and/or Kableextra: Global Table Options?

Is it possible to instruct Rmarkdown to default all tables to my styled output? Here is my attempt:
---
title: 'Test Kable Global Styling'
output:
html_document:
df_print: kable
---
```{r}
library(knitr)
library(kableExtra)
kable <- function(data) {
message("YES, IT BITES! (not sortable, but styled.)\n")
knitr::kable(data, digits=3) %>% kable_styling(bootstrap_options = "striped", full_width = F, position = "center")
}
```
## Testing
```{r}
d <- data.frame( x=1:3, y=rnorm(3) )
```
### Explicit Invokation
```{r}
kable(d)
```
### Implicit Invokation Fails
```{r}
d
```
The output looks like this:
[possibly related to How to set knitr::kable() global options in markdown for reuse, but defining my own kable function is not enough for Rmarkdown to select it.
thanks, mystery user for the complete solved update to the above problem. alas, could it generalize to :
```{r}
library(knitr)
library(DT); p <- function(...) DT::datatable(...)
knit_print.data.frame <- function(x, ...) asis_output( paste( c("",p(x)) , collapse="\n" ) )
registerS3method("knit_print", "data.frame", knit_print.data.frame)
```
# Test Code
```{r}
d <- data.frame( x=1:3, y=rnorm(3) )
```
## Print
```{r}
p(d)
d
```
done
As you saw, How to set knitr::kable() global options in markdown for reuse describes how to do this with an explicit call to kable, but doesn't handle implicit displays. The way to do that is described in the ?knitr::knit_print help page. You need code like this early in your document:
kable <- function(data, ...) {
message("YES, IT BITES! (not sortable, but styled.)\n")
knitr::kable(data, digits=3, ...) %>% kable_styling(bootstrap_options = "striped", full_width = F, position = "center")
}
knit_print.data.frame <- function(x, ...) {
res <- paste(c("", "", kable(x)), collapse = "\n")
asis_output(res)
}
registerS3method("knit_print", "data.frame", knit_print.data.frame)

rmarkdown flexdashboard images folder deletes itself

My images folder deletes itself after first knitting of the document.
I've tried self_contained = TRUE in the YAML header, doesn't work.
(I'm not sure if this makes a difference but Shiny is embedded in the dashboard)
Below is my code :
---
title : app demo
author : yeshipants
output :
flexdashboard::flex_dashboard:
orientation: rows
self_contained : TRUE
source_code: embed
runtime: shiny
---
```{r setup}
knitr::opts_chunk$set(cache = FALSE)
```
```{r loadPackages, cache = TRUE}
setwd("C:/Users/user/Desktop/Training/OCR")
library(magick)
```
Column {.sidebar data-width=350}
-------------------------------------
### Input & Parameters
```{r inputImages, cache = TRUE}
selectInput("imagesToChoose",
label = "Choose an image to process",
choices = c("Language example 1",
"Language example 2",
"Jounal example"),
selected = "Language example 1")
```
Row {.tabset}
-------------------------------------
### Original Image
```{r displayImage, cache = FALSE}
renderImage({
if (input$imagesToChoose == "Language example 1"){
list(src = "images/receipt.png", height = 240, width = 300)
}
else if(input$imagesToChoose == "Language example 2"){
list(src = "images/french.JPG", height = 240, width = 300)
}
else if(input$imagesToChoose == "Jounal example"){
list(src = "images/journal.jpg", height = 240, width = 300)
}
})
```
I think you have to do:
renderImage({
......
}, deleteFile = FALSE)

R Markdown - Positioning table and plot side by side

I am using R Markdown to output to pdf, and I am trying to get a table and a plot aligned side by side horizontally. I can get fig.align = "right" to align the plot to the right of the page, but it is plotted under the table (formatted with kable) and not side by side with it. Any tips?
Here is a way using the TeX package floatrow:
---
title: "Untitled"
header-includes:
- \usepackage{floatrow}
output:
pdf_document:
keep_tex: true
---
\newfloatcommand{btabbox}{table}
\begin{figure}[H]
\begin{floatrow}
\ffigbox{%
```{r, fig.align = "right", echo = F}
plot(mpg ~ hp, data = mtcars)
```
}{\caption{A figure}}
\btabbox{%
```{r, fig.align = "right", echo = F}
knitr::kable(head(mtcars[,1:3]), format = "latex")
```
}{\caption{A table}}
\end{floatrow}
\end{figure}
I prefer the method by Martin, but if you wanted to have a less LaTeX reliant solution, you could convert the table into a grid graphic and plot it as a subfigure:
---
header-includes:
- \usepackage{subfig}
output: pdf_document
---
```{r, fig.cap='two plots', fig.subcap= c('A figure', 'A table'), out.width = '.49\\linewidth', echo = F, fig.align='center'}
library(gridExtra)
library(grid)
plot(mpg ~ hp, data = mtcars)
grid.newpage()
grid.table(head(mtcars[,1:6]), theme = ttheme_minimal())
```
I was able to do this with a combination of the multicol package and minipages. Just another option...
Here's the code:
---
title: "Untitled"
header-includes:
- \usepackage{multicol}
- \newcommand{\btwocol}{\begin{multicols}{2}}
- \newcommand{\etwocol}{\end{multicols}}
output:
pdf_document:
keep_tex: true
---
```{r minipage_funs, echo = FALSE}
## adding minipages in Rmarkdown only seems to work for me when returned from function
fig_table_mp_start <- function() {
return("\\begin{minipage}{\\textwidth}")
}
fig_table_mp_end <- function() {
return("\\end{minipage}")
}
```
`r fig_table_mp_start()`
\btwocol
```{r, fig.align = "right", echo = FALSE}
plot(mpg ~ hp, data = mtcars)
```
```{r, fig.align = "right", echo = FALSE}
knitr::kable(head(mtcars[,1:3]), format = "latex")
```
\etwocol
`r fig_table_mp_end()`
I assume you can play around with padding to make it look pretty.

How to download plots made in a shiny app(in a jpeg /png format )

I'm trying to figure out how to use downloadButton to download a plot with shiny. The example in the package demonstrates downloadButton/downloadHandler to save a .pdf. I'm going to make a reproducible example based on that.
output$downloadPlot <- downloadHandler(
filename = function() {
"plotname .pdf"
},
content = function(file) {
pdf(file = file,
width = 12,
height = 12)
print(buildPlot())
dev.off()
}
)
I would suggest you to use Highcharter package. This way you don't need to create a download button, because the chart has options to download in several extensions. Here I give you an example of an histogram, choosing to export in PNG, SVG, JPEG or PDF.
## Export charts with Highcharter in Shiny
# Load package
library('highcharter')
# UI side
highchartOutput('plot')
# Server side
output$plot <- renderHighchart({
# Define your data, here I am using Iris dataset as example
DT <- iris$Sepal.Length
# Define export options
export <- list(
list(
text = "PNG",
onclick = JS("function () {
this.exportChart({ type: 'image/png' }); }")
),
list(
text = "JPEG",
onclick = JS("function () {
this.exportChart({ type: 'image/jpeg' }); }")
),
list(
text = "SVG",
onclick = JS("function () {
this.exportChart({ type: 'image/svg+xml' }); }")
),
list(
text = "PDF",
onclick = JS("function () {
this.exportChart({ type: 'application/pdf' }); }")
)
)
# Plot histogram
hchart(DT,
type = "area",
name = colnames(iris[1])
) %>%
hc_exporting(
enabled = TRUE,
formAttributes = list(target = "_blank"),
buttons = list(contextButton = list(
text = "Export",
theme = list(fill = "transparent"),
menuItems = export
))
)
})
The output should be something like this:
Hope this helps.
Wlademir.