Martin Schmelzer
Martin Schmelzer

Reputation: 23909

Knitr: Show source code of inline code chunks

When writing lecture slides for example, we very often encounter a situation where we would like to have an inline code output to be source code = result. So for example

"foofoofoo qt(p = 0.95, df = 24) = 1.710882 barbarbar"

But \Sexpr{qt(p = 0.95, df = 24)} only delivers the second part of that output. One of a few workarounds is

\Sexpr{highr::hi_latex('qt(p = 0.95, df = 24)')} $=$ \Sexpr{qt(p = 0.95, df = 24)} 

which is a little uncomfortable to use.

Question 1: Is there another solution?

Question 2:

The inline hook only allows us to change the formatting of the evaluation result (so how the 1.710882 above should be displayed).

Would it be possible to make the source code in \Sexpr{} available as an option inside the inline hook? Then I could easily define the inline output to be source = result.

Upvotes: 5

Views: 190

Answers (1)

Consistency
Consistency

Reputation: 2922

I guess it's possible to achieve what you want by modifying hooks, but only modifying inline hook is not enough, since the only argument passed to the inline hook is already the evaluated result and no any other argument. And modifying a lot of hooks is too risky and not worth it. Here is something which achieves what you want with little effort. For example, you can define the following function s in your knitr setup chunk:

s <- function(x){
    paste0(deparse(substitute(x)), " = ", x)
}

And then you can use something like r s(qt(p = 0.95, df = 24)) or \Sexpr{s(qt(p = 0.95, df = 24))} to get the result you want.

Edit: a more sophisticated way may be:

s <- function(x){
    paste0(deparse(substitute(x)), " = ", knitr::knit_hooks$get("inline")(x))
}

This version of s will give your rounded numeric results just as the default inline hook.

Edit: Thanks to @user2554330, I change deparse(sys.call()[[2]] to deparse(substitute(x)) following a more common R idiom.

Upvotes: 4

Related Questions