Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cross-referencing gt tables does not work when knitting to PDF #818

Closed
camillebelmin opened this issue Jul 27, 2021 · 4 comments
Closed

Comments

@camillebelmin
Copy link

camillebelmin commented Jul 27, 2021

Hi,
Thanks a lot for making progress on the gt package to allow cross referencing within bookdown documents. However, I have the impression that it still does not work for PDFs. In the reproducible example below, cross-reference did not work when knitting to bookdown::pdf_document2 (resulting in "Table ??"). It only worked when knitting to bookdown::html_document2 (resulting in "Table 1"). Could you please let me know if there is a trick to make it work with PDF, or whether cross-ref for PDF is planned to be developed in the near future?

I am now referencing Table \@ref(tab:label)

```{r label }
df = data.frame(A = c(1,2,3), B = c(4,5,6))

gt(df, caption = "this is the caption")
```

Originally posted by @camillebelmin in #115 (comment)

@earcanal
Copy link

earcanal commented Feb 22, 2022

I don't get a caption or table number in this MWE:

---
blind: true
title: |
  MWE
always_allow_html: true
output:
  bookdown::pdf_document2:
    toc: false
    number_sections: false
    latex_engine: lualatex
    template: null
    keep_tex: true
header-includes:
      \usepackage{amsmath}
      
      \usepackage{booktabs}
      
      \usepackage{caption}
      
      \usepackage{longtable}
documentclass: article
link-citations: true
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)

library(tidyverse)
library(gt)
```

If Table \@ref(tab:mwe) has a caption, then `gt` can probably be used in `bookdown`.

```{r mwe, results='asis'}
df = data.frame(A = c(1,2,3), B = c(4,5,6))
gt(df, caption = "this is the caption") %>% as_latex() %>% as.character() %>% cat()
```

... and the LaTeX generated:

% Options for packages loaded elsewhere
\PassOptionsToPackage{unicode}{hyperref}
\PassOptionsToPackage{hyphens}{url}
%
\documentclass[
]{article}
\usepackage{amsmath,amssymb}
\usepackage{lmodern}
\usepackage{ifxetex,ifluatex}
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
  \usepackage[T1]{fontenc}
  \usepackage[utf8]{inputenc}
  \usepackage{textcomp} % provide euro and other symbols
\else % if luatex or xetex
  \usepackage{unicode-math}
  \defaultfontfeatures{Scale=MatchLowercase}
  \defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
\fi
% Use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\IfFileExists{microtype.sty}{% use microtype if available
  \usepackage[]{microtype}
  \UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\makeatletter
\@ifundefined{KOMAClassName}{% if non-KOMA class
  \IfFileExists{parskip.sty}{%
    \usepackage{parskip}
  }{% else
    \setlength{\parindent}{0pt}
    \setlength{\parskip}{6pt plus 2pt minus 1pt}}
}{% if KOMA class
  \KOMAoptions{parskip=half}}
\makeatother
\usepackage{xcolor}
\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
\IfFileExists{bookmark.sty}{\usepackage{bookmark}}{\usepackage{hyperref}}
\hypersetup{
  pdftitle={MWE},
  hidelinks,
  pdfcreator={LaTeX via pandoc}}
\urlstyle{same} % disable monospaced font for URLs
\usepackage{longtable,booktabs,array}
\usepackage{calc} % for calculating minipage widths
% Correct order of tables after \paragraph or \subparagraph
\usepackage{etoolbox}
\makeatletter
\patchcmd\longtable{\par}{\if@noskipsec\mbox{}\fi\par}{}{}
\makeatother
% Allow footnotes in longtable head/foot
\IfFileExists{footnotehyper.sty}{\usepackage{footnotehyper}}{\usepackage{footnote}}
\makesavenoteenv{longtable}
\setlength{\emergencystretch}{3em} % prevent overfull lines
\providecommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
\usepackage{amsmath}
\usepackage{booktabs}
\usepackage{caption}
\usepackage{longtable}
\ifluatex
  \usepackage{selnolig}  % disable illegal ligatures
\fi

\title{MWE}
\author{}
\date{\vspace{-2.5em}}

\begin{document}
\maketitle

If Table \ref{tab:mwe} has a caption, then \texttt{gt} can probably be used in \texttt{bookdown}.

\captionsetup[table]{labelformat=empty,skip=1pt}
\begin{longtable}{rr}
\toprule
A & B \\ 
\midrule
1 & 4 \\ 
2 & 5 \\ 
3 & 6 \\ 
\bottomrule
\end{longtable}

\end{document}
> sessionInfo()
R version 4.0.4 (2021-02-15)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 21.04

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C               LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8     LC_MONETARY=en_GB.UTF-8   
 [6] LC_MESSAGES=en_GB.UTF-8    LC_PAPER=en_GB.UTF-8       LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] gt_0.4.0.9000          forcats_0.5.1          stringr_1.4.0          dplyr_1.0.8            purrr_0.3.4            readr_2.0.0           
 [7] tidyr_1.1.4            tibble_3.1.6           ggplot2_3.3.5          tidyverse_1.3.1        BayesFactor_0.9.12-4.2 Matrix_1.3-2          
[13] coda_0.19-4           

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.7         lubridate_1.7.10   mvtnorm_1.1-2      lattice_0.20-41    gtools_3.9.2       assertthat_0.2.1   digest_0.6.29     
 [8] utf8_1.2.2         R6_2.5.1           cellranger_1.1.0   backports_1.4.1    MatrixModels_0.5-0 reprex_2.0.0       evaluate_0.14     
[15] httr_1.4.2         pillar_1.7.0       rlang_1.0.1        readxl_1.3.1       rstudioapi_0.13    rmarkdown_2.9      munsell_0.5.0     
[22] broom_0.7.8.9000   compiler_4.0.4     modelr_0.1.8       xfun_0.27          pkgconfig_2.0.3    htmltools_0.5.2    tidyselect_1.1.2  
[29] bookdown_0.22      fansi_1.0.2        crayon_1.5.0       tzdb_0.1.2         dbplyr_2.1.1       withr_2.4.3        grid_4.0.4        
[36] jsonlite_1.7.2     gtable_0.3.0       lifecycle_1.0.1    DBI_1.1.1          magrittr_2.0.2     scales_1.1.1       cli_3.2.0         
[43] stringi_1.7.6      pbapply_1.4-3      fs_1.5.2           xml2_1.3.2         ellipsis_0.3.2     generics_0.1.2     vctrs_0.3.8       
[50] tools_4.0.4        glue_1.6.1         hms_1.1.0          yaml_2.2.1         parallel_4.0.4     fastmap_1.1.0      colorspace_2.0-3  
[57] rvest_1.0.0        knitr_1.36         haven_2.4.1   

@rich-iannone rich-iannone added this to the FUTURE milestone Aug 22, 2022
@hansvancalster
Copy link

Here is a workaround - specifically for bookdown in combination with gt- that did the trick for me:

---
title: "Untitled"
author: ""
date: "`r Sys.Date()`"
output:
  bookdown::html_document2:
    toc: true
  bookdown::pdf_document2:
    toc: true
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(gt)
```


## Table caption with `gt` for pdf or html output


Table \@ref(tab:cars-table)

(ref:cars-table) The cars data set


```{r custom-function}
as_latex_with_caption <- function(gt, chunk_label) {
  gt <- gt::as_latex(gt)
  caption <- paste0(
    "\\caption{\\label{tab:", chunk_label, "}(ref:", chunk_label, ")}\\\\")
  latex <- strsplit(gt[1], split = "\n")[[1]]
  latex <- c(latex[1], caption, latex[-1])
  latex <- paste(latex, collapse = "\n")
  gt[1] <- latex
  return(gt)
}
```

```{r cars-table}
if (knitr::is_latex_output()) {
  gt(cars) %>%
    as_latex_with_caption("cars-table")
}
if (knitr::is_html_output()) {
  gt(cars, caption = "(ref:cars-table)")
}
```


@olivroy
Copy link
Collaborator

olivroy commented Jul 12, 2024

You are likely to be better off using Quarto LaTeX output. The support for cross-references is done natively.

@olivroy
Copy link
Collaborator

olivroy commented Aug 29, 2024

the development version of gt now includes a fix for this, thanks to @nielsbock, in case people want to try it out!

pak::pak("rstudio/gt")

We'd love to receive your feedback so please open a new issue if something is not working as expected.

@olivroy olivroy closed this as completed Aug 29, 2024
@olivroy olivroy modified the milestones: FUTURE, v0.12.0 Aug 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants