knitr
knitr copied to clipboard
Show one line of code but result from another line without adding any comment
Tested from https://github.com/quarto-dev/quarto-cli/issues/863#issuecomment-1132597488
mtcars rmarkdown::paged_table(mtcars)
Can I show 'mtcars' in the code chunk after the render but not 'rmarkdown::paged_table(mtcars)' and in addition to that have only the result of the paged_table() shown?
At first I tried
```{r, echo = -2, eval= 2}
mtcars
rmarkdown::paged_table(mtcars)
```
but it will add a ##
prefix, without option to opt-out
https://github.com/yihui/knitr/blob/ca398c2de670bf67741627de51c3ba8f4db12937/R/block.R#L235-L240
## mtcars
I would have thought this could be equivalent of this
```{r, eval= FALSE}
mtcars
```
```{r, echo = FALSE}
rmarkdown::paged_table(mtcars)
```
I already encountered this in demo slide when trying to show an example I think. Would it be interesting to add chunk option to allow this ?
Maybe the longer form in two chunks is enough... 🤔
I remember @jaredlander also requested this feature eight or nine years ago at a Strata conf (time flies), i.e., evaluate and echo different lines of code in the same chunk. I didn't do it because I thought it would be a little tricky to implement, and also felt like "cheating" :) Since this was brought up again, I think we can reconsider implementing it. Basically, after evaluate()
ing the code, we remove the ##
from the source code expressions with indices setdiff(iss, iss[ev])
; or we use a special comment like #~
/ #*
etc to mask the code instead of ##
, then simply remove these comment masks (this will be a little easier implementation-wise).
@cderv Do you want to try it, or you would rather me do it? I won't have time until a few weeks later.
I'll give it a try following your advice.
I would rather suggest use the render
chunk option.
It has finer control and is less tricky.
Things like {r, echo=-2, eval= 2}
is not a good idea because author has to correct the values when line number changes.
```{r, render = function(x, ...) knitr::knit_print(rmarkdown::paged_table(x), ...)}
mtcars
```
For this particular case, yes, the problem can be solved by a custom render
function. For general cases, we still need a more general solution.