I am trying to use the function kable_as_image, which from my understanding will save the table as a image. My results though is not a table, dont know if I am doing something wrong as I cant find an example.
---
title: "Untitled"
author: "Test"
date: '2017-11-29'
output: pdf_document
---
```{r}
library(knitr)
library(kableExtra)
```
```{r}
kable_as_image(kable(head(iris)), filename = "~/Documents/.../.../pic")
```
#warning: kpathsea: gloss-$mainlang$.ldf: Unrecognized variable construct `$.'.
What my "picture" looks like:
Now I feel like kable_as_image is a somehow misleading name for the function. As explained in the doc, as least right now, it only works for latex tables, try kable_as_image(kable(..., format = "latex", booktabs = T), filename = "pic").
Related
I have a .Rmd file which I am converting to PDF. For layout reasons, I want to display the generated output plot of my code chunk on the next page even though it would just fit in underneath.
Normally with text etc. one would use
\pagebreak
But how can I signalize the code chunk that it should display its output on the next page?
Thanks for helping!
You can write a knitr hook to set up a chunk option to do this.
So here I have modified the source chunk hook and created a chunk option next_page which, if TRUE, the output of that chunk will be on the next page.
---
title: "Chunk Output in Next page"
output: pdf_document
date: "2022-11-25"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
```{r, include=FALSE}
library(knitr)
default_source_hook <- knit_hooks$get('source')
knit_hooks$set(
source = function(x, options) {
if(isTRUE(options$next_page)) {
paste0(default_source_hook(x, options),
"\n\n\\newpage\n\n")
} else {
default_source_hook(x, options)
}
}
)
```
```{r, next_page=TRUE}
plot(mpg ~ disp, data = mtcars)
```
I would recommend you to save the output in the file (png/jpeg/pdf) and then load it with the markdown or knitr.
Such solution gives you a full control.
Automatic
I found alternative solution in rmarkdown-cookbook.
We generate a plot in this code chunk but do not show it:
```{r cars-plot, dev='png', fig.show='hide'}
plot(cars)
```
\newpage
![A nice plot.](\`r knitr::fig_chunk('cars-plot', 'png')\`)
Manual
```{r}
png("NAME.png")
# your code to generate plot
dev.off()
```
then load image with
![LABEL](PATH/NAME.png) or with
```{r echo=FALSE, out.width='100%', ...}
knitr::include_graphics('PATH/NAME.png')
```
I've provided a minimal reproducible example below. I'm currently trying to use the R quarto package to pass a logical parameter into the Quarto chunk options.
Below is the quarto document, where I created 2 parameters, show_code, and show_plot.
---
title: "Untitled"
format: html
params:
show_code: TRUE
show_plot: TRUE
---
```{r, echo=params$show_code}
summary(cars)
```
```{r, include=params$show_plot}
plot(pressure)
```
This document would render properly via the render button in R studio.
However, when trying to render this document via the quarto_render() function from the R quarto package, this would fail.
library(quarto)
quarto::quarto_render(
input = 'qmd_document.qmd',
output_format = 'html',
output_file = 'qmd_document_with_code.html',
execute_params = list(show_plot = TRUE,
show_code = TRUE)
)
It appears that a character yes is passed instead of the logical TRUE or FALSE to both Chunk 1 and Chunk 2 in the console.
How do I properly pass the logical characters to a parameterized Quarto report chunk options via quarto_render()?
Option 1 (Using chunk options in chunk header)
We can use logical statement in chunk option (as we do in r-markdown).
parameterized_report.qmd
---
title: "Using Parameters"
format: html
params:
show_code: "yes"
show_plot: "yes"
---
```{r, echo=(params$show_code == "yes")}
summary(cars)
```
```{r, include=(params$show_plot == "yes")}
plot(pressure)
```
Then from either r-console/rscript file, we call quarto_render using params "yes" or "no",
quarto::quarto_render(
input = 'parameterized_report.qmd',
output_format = 'html',
output_file = 'qmd_document_with_code.html',
execute_params = list(show_plot = "yes",
show_code = "no")
)
Option 2 (Using YAML syntax chunk option)
Note that, above we have used the chunk option in the chunk header which works fine with knitr engine, but quarto prefers comment-based yaml syntax (i.e. using #|). As per the quarto documentation
Note that if you prefer it is still possible to include chunk options on the first line (e.g. ```{r, echo = FALSE}). That said, we recommend using the comment-based syntax to make documents more portable and consistent across execution engines. Chunk options included this way use YAML syntax rather than R syntax for consistency with options provided in YAML front matter. You can still however use R code for option values by prefacing them with !expr
So following the quarto preferred way, we can use parameters like this,
parameterized_report.qmd
---
title: "Using Parameters"
format: html
params:
show_code: "false"
show_plot: "false"
---
```{r}
#| echo: !expr params$show_code
summary(cars)
```
```{r}
#| include: !expr params$show_plot
plot(pressure)
```
then use quarto_render with "true" or "false"
quarto::quarto_render(
input = 'parameterized_report.qmd',
output_format = 'html',
output_file = 'qmd_document_with_code.html',
execute_params = list(show_plot = "true",
show_code = "true")
)
Lastly, note two things,
here we have used "true" or "false", since echo, include, eval takes value true/false instead of TRUE/FALSE in this comment-based syntax.
Additionally, Since knitr 1.35, knitr engine also supports this comment based syntax. See News from knitr v1.35 to v1.37: Alternative Syntax for Chunk Options
I have seen a tutorial by which one can change the way tables are printed to knitr::kable() format. Is it possible to do the same with the rmarkdown::paged_table() format, so that all tables by default will be printed in paged_table() format as in the {rmarkdown} package in R?
I had the same problem in Quarto and the solution is to use df-print: paged (note df-print not df_print) in the yaml file.
Eg.
---
title: "Untitled"
editor: visual
format:
html:
df-print: paged
---
```{r}
data.frame(
x = 1:10,
y = rnorm(10)
)
```
which results in this
In case of Rmarkdown the answer offered by #VishalKatti is IMHO the way to go. For Quarto (or RMarkdown), adapting the example in the R Markdown Cookbook one option to achieve your desired result may look like so:
---
title: Use a custom `knit_print` method to print data frames
format: html
---
First, we define a `knit_print` method, and register it:
```{r}
knit_print.data.frame = function(x, ...) {
res = rmarkdown::paged_table(x)
rmarkdown:::knit_print.data.frame(res)
}
registerS3method(
"knit_print", "data.frame", knit_print.data.frame,
envir = asNamespace("knitr")
)
```
Now we can test this custom printing method on data frames.
Note that you no longer need to call `rmarkdown::paged_table()`
explicitly.
```{r}
head(iris)
```
```{r}
head(mtcars)
```
Put this in the yaml.
output:
html_document:
df_print: paged
To complete the answer shared above, here are several ways to achieve this
Using a printing function for knitr
For paged table this would be this function: (which is used internally by rmarkdown for the df_print feature)
paged_print <- function(x, options) {
knitr::asis_output(
rmarkdown:::paged_table_html(x, options = attr(
x,
"options"
)),
meta = list(dependencies = rmarkdown::html_dependency_pagedtable())
)
}
This is similar to the function in the other answer, it is just that rmarkdown:::knit_print.data.frame does more than juts handling paged tables.
Then you could register it in a document so that it is applied by default for any data.frame printing.
registerS3method(
"knit_print", "data.frame", paged_print,
envir = asNamespace("knitr")
)
or use it on chunk basis where you need to print a data.frame in a single value chunk. (
```{r, render = paged_print}
iris
```
More on custom printing method for knitr its vignette
Using option hooks for knitr
A df_print chunk option can also be simulated this way using a option hook
knitr::opts_hooks$set(df_print = function(options) {
if (options$df_print == "paged") {
options$render = paged_print
}
options
})
this will allow something like
```{r, df_print = "paged"}
iris
```
```{r}
iris
```
First table will be shown as paged table
Second table will be show as usual data.frame
The problem is simple - How do I insert a variable filename into an rmarkdown PDF? I want to do this:
---
FNL = "image.png"
---
![Some Text](params$FNL)
only I need to pass in the value for FNL when calling rmarkdown::render
The purpose is to give the image a unique ID so that users get images marked for their session.
Anyone able to help with this?
Just use inline R evaluation (works for both HTML and PDF output):
---
title: "Example"
author: "Martin"
date: "March, 11 2017"
output: html_document
params:
img: NULL
---
`r sprintf("![A good boy](%s)", params$img)`
Then you can render the document with the image file by calling
rmarkdown::render("MyDocument.Rmd", params = list(img = "unnamed.png")).
How can I programmatically set a figure caption in a knitr hook?
I'd like to set the figure caption, if not explicitly defined, to the chunk label. I've read the knitr docs on options, options, and hooks, and though I think I understand the mechanisms at play, I can't get it to work.
My use-case that perhaps justifies this behavior: my work-flow recently adapted to start my data and visualization exploration in Rmd files. I'll use chunks for cleaning, subsetting, etc, and then a sample chunk for each visualization. This is quick and dirty, meaning minimal markdown. When I look over the report (typically rendered into PDF), I'll look at a figure and want to go straight to the source for it. Though text before/after the figure can provide insight, due to LaTeX figure rules it is not a sure thing. Counting figure numbers is feasible, but not "easy" (and becomes problematic with many figures). Captions are always with the figure, so it'd be great if I can default to filling the caption with the chunk label. (Yes, it's a little lazy of me.)
The MWE is below.
The hook code ran just fine; the returned strings in the hook appeared correctly. However, the figure caption did not change. Exception: when there is a chunk with an undefined fig.cap, all subsequent chunks have their caption set to the first un-captioned chunk name; this doesn't surprise me due to the global nature of opts_chunk, so that's out.
I suspect it might be related to "output hooks" vice "chunk hooks," but this really is a per-chunk thing and I do not want to modify the plot, just set the caption.
MWE:
---
title: "Document Title"
author: "My Name"
output:
pdf_document:
fig_caption: yes
---
# Header
```{r setup}
knit_hooks$set(autocap = function(before, options, envir) {
if (before) {
if (is.null(options$fig.cap)) {
options$fig.cap <- options$label
knitr::opts_current$set(fig.cap = options$label)
knitr::opts_chunk$set(fig.cap = options$label) # wrong!
paste('Set: `', options$label, '`, `',
knitr::opts_current$get('fig.cap'), '`', sep = '')
} else {
paste('Kept: `', options$fig.cap, '`', sep = '')
}
}
})
opts_chunk$set(autocap = TRUE)
```
## No Plot
```{r textOnly}
1+1
```
## Caption Already Set
```{r someplot, fig.cap='someplot caption'}
plot(0)
```
## Caption Not Set
```{r anotherPlot}
plot(1)
```
Is it ok like this ? I simply modify the knitr internal function .img.cap function which can be found here.
```{r}
.img.cap = function(options) {
if(is.null(options$fig.cap)) options$label else options$fig.cap
}
assignInNamespace(".img.cap", .img.cap, ns="knitr")
```
Does it help ?
```{r}
library(knitr)
knit_hooks$set(htmlcap = function(before, options, envir) {
if(!before) {
caption <- ifelse(is.character(options$htmlcap), options$htmlcap, options$label)
paste('<p class="caption">', caption, "</p>", sep="")
}
})
```
```{r Hello, htmlcap=TRUE}
library(ggplot2)
ggplot(diamonds,aes(price,carat)) + geom_point()
```
```{r, htmlcap="Hello again"}
ggplot(diamonds,aes(price,carat)) + geom_point()
```