Knitr: show source code of inline code snippets

When writing lecture slides, for example, we very often encounter a situation where we want the output of inline code to be source code = result . For example,

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

But \Sexpr{qt(p = 0.95, df = 24)} performs only the second part of this output. One of several workarounds is

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

which is a bit inconvenient to use.

Question 1: Is there another solution?

Question 2:

The built-in hook allows us to change the formatting of the evaluation result (as shown above 1.710882 ).

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

+5
source share
1 answer

I assume that you can achieve what you want by modifying the hooks, but just modifying the built-in hook is not enough, since the only argument passed to the built-in hook is already an evaluated result and no other argument. And modifying a large number of hooks is too risky and not worth it. Here is something that allows you with minimal effort. For example, you can define the following function s in your knitr tuner:

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

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

Edit: A more complicated way could be:

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

This version of s will give your rounded numerical results just like the built-in hook by default.

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

+4
source

Source: https://habr.com/ru/post/1269212/


All Articles