yihui / knitr

A general-purpose tool for dynamic report generation in R
https://yihui.org/knitr/
2.36k stars 873 forks source link

`tab.cap` in `eval.after` not evaluating R code properly #2352

Open rikudoukarthik opened 2 weeks ago

rikudoukarthik commented 2 weeks ago

Firstly, apologies for the huge delay in responding---this is following on from #2305 which got locked after inactivity.

While @yihui showed how eval.after = "tab.cap" can be included in the knitr::opts_knit$set() call, the issue is still unresolved because the tab.cap is not functioning as expected. Please see the small reprex below (add a single ` to chunk open and close calls).

---
title: "Test"
output: 
  bookdown::word_document2:
editor_options: 
  chunk_output_type: console
---

```{r, echo=FALSE}

library(glue) 

knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
knitr::opts_knit$set(eval.after = "tab.cap")

# function to add commas to big numbers in one go
good_num <- function(number) {

  if (number < 10) {
    xfun::numbers_to_words(number)
  } else {
    format(number, big.mark = ",", scientific = FALSE)
  }

}

cap_x <- good_num(12345)

library(tidyverse)
library(flextable)

cap_y <- good_num(45678)

iris %>% 
  slice(1:10) %>% 
  flextable()


Ideally, assuming `fig.cap` behaviour, the caption for the above table should read "This is my caption; neither 12,345 or 45,678 appears.", but instead I get this:

![image](https://github.com/yihui/knitr/assets/61746688/a6033b47-ee70-40ae-bf11-9943d742c9e7)

Why is `tab.cap` not behaving as `fig.cap` does? 
yihui commented 2 weeks ago

That's because fig.cap is needed only after a chunk has finished evaluation. Generating the figure is done after a chunk's evaluation is done. However, for the table case here, it's different: the table caption is needed (by flextable()) in the middle of the chunk evaluation.

add a single ` to chunk open and close calls

Please read the issue guide when filing issues.

rikudoukarthik commented 1 week ago

Interesting, I didn't consider that! So the eval.after option doesn't work for flextable()?

Also, even if the table caption is evaluated in the middle of chunk evaluation, cap_x is already assigned in the previous chunk, so how come that doesn't appear either?