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
.
To insert a code chunk, press Ctrl + Alt + I in the source pane (top left pane in the default settings of RStudio). A code chunk will appear: Inside the code chunk you can write and run R-code.
The first code chunk: ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` is used to specify any global settings to be applied to the R Markdown script. The example sets all code chunks as “echo=TRUE”, meaning they will be included in the final rendered version.
Hide source code: ```{r, echo=FALSE} 1 + 1 ``` Hide text output (you can also use `results = FALSE`): ```{r, results='hide'} print("You will not see the text output.") ``` Hide messages: ```{r, message=FALSE} message("You will not see the message.") ``` Hide warning messages: ```{r, warning=FALSE} # this will generate ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With