I just ran into this question, which I tried to answer about two years ago, and thought about how to get the code and its evaluated output in one built-in statement. We just need a helper function. The following is an example. The code is entered as a text string, and the function returns both the code and the result of the code evaluation:
--- title: "RMarkdown teaching demo" author: "whoever" output: pdf_document --- ```{r} fnc = function(expr) { paste(expr, " = ", eval(parse(text=expr))) }
Below is the result.

This works, but there are two problems. Firstly, the code is not in a monospace font. Secondly, the code is not highlighted in gray.
I thought I could get a monospace font with the latex tag \texttt{} .
```{r} fnc = function(expr) { paste("\\texttt{", expr, " = ", eval(parse(text=expr)), "}", sep="") } ```
It seems that it returns the desired line when interactively launched ( "\\texttt{sum(is.na(iris$Sepal.Length)) = 3}" ), but when trying to knit the document produces the following error:
! Extra }, or forgotten $. <recently read> \egroup l.163 ...texttt{sum(is.na(iris$Sepal.Length)) = 3}
It seemed to me that I can highlight the shortcut 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, again this causes 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 problems when used with plain text inside an rmarkdown document.
So, I'm not sure how to get a monospaced font or selected text, but at least it takes a step towards code + evaluated code from one built-in R operator. I hope someone with more knowledge of language calculation and latex release markup, can give more information on how to make it work as you wish.