2

I am trying to put a margin note in my Tufte Latex document that is partially generated by r code, but have been unsuccessful. Code blocks set to print in the margin only seem to put plots there, not text or tables. Margin notes called with tufte::marginfigure() throw an error if they have inline code in them. And margin figure blocks ignore inline code. I have been successful getting my code-generated text to print in the margin with a footnote, but then I get footnote numbering, which I don't want. I thought of turning off numbering on that footnote, but haven't been able to.

Here's an example:

---
title: "Tufte Test"
author: "Neal"
date: "`r Sys.Date()`"
output:
  tufte::tufte_handout: default
---

```{r setup, include=FALSE}
library(tufte)
library(tidyverse)
```

Here is some normal text with inline code: 2+3=`r 2+3`  

\vspace{10pt}
```{r block, fig.margin=TRUE, echo=FALSE, results='asis'}
cat('Here is a margin code block with code-generated text and a plot.')
mtcars %>% ggplot(aes(mpg, disp)) + geom_point()
cat('The text stays in the main body.')
```


\vspace{10pt}
I can combine text and code in a footnote^[2+3=`r 2+3` \newline\vspace{10pt}], but I get footnote numbering, which I don't want.

```{marginfigure, echo=TRUE}
Here is a margin figure with inline code that doesn't work: 2+3=`r 2+3` \newline\vspace{10pt}
```


`r tufte::margin_note('This is a margin note. If I try to include inline code in it, I get an error because it "failed to tidy R code in chunk"')`

And the output: tufte-test.pdf

Any ideas? Thanks.

nealmaker
  • 157
  • 8

1 Answers1

4

The code chunk labelled marginfigure just wraps the contents in the LaTeX environment called marginfigure. You can do that yourself, and then the inline code will be processed properly.

That is, you replace this:

```{marginfigure, echo=TRUE}
Here is a margin figure with inline code that doesn't work: 2+3=`r 2+3` \newline\vspace{10pt}
```

with this:

\begin{marginfigure}
Here is a margin figure with inline code that *does* work: 2+3=`r 2+3` \newline\vspace{10pt}
\end{marginfigure}

Your first example is a bit more complicated. It needs to be broken into three parts:

\begin{marginfigure}
`r 'Here is a margin code block with code-generated text.'`
\end{marginfigure}

```{r block, fig.margin=TRUE, echo=FALSE}
mtcars %>% ggplot(aes(mpg, disp)) + geom_point()
```

\begin{marginfigure}
`r 'The text doesn\'t stay in the main body.'`
\end{marginfigure}

You asked for PDF output, but just for the sake of completeness, if you were using tufte::tufte_html for HTML output instead, the equivalent result would be obtained using

<span class="marginnote">
Here is a margin figure with inline code that *does* work: 2+3=`r 2+3`
</span>
user2554330
  • 37,248
  • 4
  • 43
  • 90