John Gagnon
John Gagnon

Reputation: 915

How do I use variables for chunk options?

I am attempting to evaluate a variable after executing an R chunk to define the size chunk options.

---
title: "R Notebook"
output:
  pdf_document: default
  html_notebook: default
---

```{r setup}
library("tidyverse")

theme_set(theme_bw())
theme_update(strip.background = element_blank())

knitr::opts_chunk$set(out.width = "80%",
                      out.height = "80%",
                      eval.after = c("fig.height", "fig.width"))
```

# Example chunk attempting to eval.after

```{r fig.width=figWidth, fig.height=figHeight}
plt <- ggplot(iris,
       aes(x = Sepal.Length,
           y = Sepal.Width,
           color = Petal.Length/Petal.Width)) +
  geom_point() +
  facet_wrap(~Species, ncol = 1)
figWidth <- 7*max(ggplot2::ggplot_build(plt)$layout$layout$COL)
figHeight <- 3.5*max(ggplot2::ggplot_build(plt)$layout$layout$ROW)
plt
```

Example of the error:

Calls: <Anonymous> ... process_group.block -> call_block -> eval_lang -> eval -> eval
Execution halted

enter image description here

I see that I get two main error: one from quartz() device and one from R Markdown. The quartz() error occurs regardless of whether I try to use the variables from the same code chunk or if I try to use call the variables in a subsequent chunk

```{r fig.width=figWidth, fig.height=figHeight}
plt
```

Upvotes: 3

Views: 608

Answers (1)

alistaire
alistaire

Reputation: 43354

As documented here eval.after is a package option, not a chunk option, so you need to set it with knitr::opts_knit$set(eval.after = ...). For example,

---
title: "eval.after"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_knit$set(eval.after = 'comment')
```

```{r chunk1, comment=comment_str}
comment_str <- '#$'
1 + 2
```

```{r foo, comment=comment_str}
comment_str <- '#>'
3 + 4
```

knits to

knitted document with comment strings defined in chunks

Upvotes: 1

Related Questions