knitr icon indicating copy to clipboard operation
knitr copied to clipboard

Show one line of code but result from another line without adding any comment

Open cderv opened this issue 2 years ago • 4 comments

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... 🤔

cderv avatar May 20 '22 09:05 cderv

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.

yihui avatar May 23 '22 16:05 yihui

I'll give it a try following your advice.

cderv avatar May 23 '22 16:05 cderv

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
```

atusy avatar Jul 25 '22 23:07 atusy

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.

yihui avatar Jul 26 '22 04:07 yihui