Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make inline r script visible in RMarkdown report?

Tags:

r

r-markdown

Suppose that the command isn't important enough to have it on the separate line, But I still want it to be visible along the result, I know there is ` r inlinestr` in R Markdown, but it I can't pass echo=T to it. I want the result to be something like this:

enter image description here

like image 957
Scientist1642 Avatar asked Sep 26 '22 07:09

Scientist1642


1 Answers

I just ran across this question that I attempted to answer about two years ago and thought of a way to get both the code and its evaluated output in a single inline statement. We just need a helper function. Below is an example. The code is entered as a text string and the function returns both the code and the result of evaluating the code:

---
title: "RMarkdown teaching demo"
author: "whoever"
output: pdf_document
---

```{r}
fnc = function(expr) {
  paste(expr, " = ", eval(parse(text=expr)))
}

# Add some missing values
iris$Sepal.Length[c(3,5,10)] = NA
```

f. There are `r fnc("sum(is.na(iris$Sepal.Length))")` missing height values.

Below is the output.


enter image description here


It works, but there are two issues. First, the code is not in monospace font. Second, the code is not highlighted with a gray background.

I thought that I could get monospace font with the latex \texttt{} tag.

```{r}
fnc = function(expr) {
  paste("\\texttt{", expr, " = ", eval(parse(text=expr)), "}", sep="")
}
```

This appears to return the desired string when run interactively ("\\texttt{sum(is.na(iris$Sepal.Length)) = 3}"), but throws the following error when I try to knit the document:

! Extra }, or forgotten $.
<recently read> \egroup

l.163 ...texttt{sum(is.na(iris$Sepal.Length)) = 3}

I thought I could get highlighting with the \hl{} tag (which also requires \usepackage{color, soul} in the latex header):

```{r}
fnc = function(expr) {
  paste("\\hl{", expr, " = ", eval(parse(text=expr)), "}", sep="")
}
```

However, once again, this throws an error:

! Argument of \SOUL@addmath has an extra }.
<inserted text> 
                \par 
l.161 ...re \hl{sum(is.na(iris$Sepal.Length)) = 3}

Both texttt{} and \hl{} work without a problem when used with regular text inside an rmarkdown document.

So, I'm not sure how to get the monospace font or highlighted text, but at least this takes a step toward code + evaluated code from a single inline R statement. Hopefully, someone with more knowledge of computing on the language and outputting latex markup can provide more insight into how to get this to work as desired.

like image 154
eipi10 Avatar answered Sep 28 '22 05:09

eipi10