Coder Social home page Coder Social logo

haozhu233 / kableextra Goto Github PK

View Code? Open in Web Editor NEW
676.0 25.0 144.0 22.79 MB

Construct Complex Table with knitr::kable() + pipe.

Home Page: https://haozhu233.github.io/kableExtra/

License: Other

R 98.10% JavaScript 0.10% CSS 1.80%
rmarkdown kable html latex knitr kableextra

kableextra's Introduction

kableExtra logo

CRAN_version CRAN_download CRAN_download_total DOI R-CMD-check


When we are talking about table generators in R, knitr's kable() function is usually a popular choice because of its ultimate simplicity. Unlike those powerful table rendering engines such as xtable, the philosophy behind knitr::kable() is to make it easy for programmers to use. Just as it claimed in its function description,

This is a very simple table generator. It is simple by design. It is not intended to replace any other R packages for making tables. - Yihui

However, the ultimate simplicity of kable() also brought troubles to some of us, especially for new R users, who may not have a lot of experience on generating tables in R. It is not rare to see people including experienced users asking questions like how to center/left-align a table on Stack Overflow. Also, for me personally, I found myself repeatedly parsing CSS into kable() for some very simple features like striped lines. For LaTeX, it's even worse since I'm almost Stack Overflow dependent for LaTeX... That's why this package kableExtra was created.

I hope with kableExtra, you can

  • Use default base kable() (Or a good alternative for markdown tables is pander::pander()) for all simple tables
  • Use kable() with kableExtra to generate 90 % of complex/advanced/self-customized/beautiful tables in either HTML or LaTeX
  • Only have to mess with raw HTML/LaTeX in the last 10% cases where kableExtra cannot solve the problem

This package can load required LaTeX package automatically in vanilla R Markdown. For customized R Markdown templates, it is recommended to load related LaTeX packages manually.


Features

Pipable syntax

kableExtra is NOT a table generating package. It is a package that can "add features" to a kable() output using a syntax that every useR loves - the pipes %>%. We see similar approaches to deal with plots in packages like ggvis and plotly. There is no reason why we cannot use it with tables.

Unified functions for both HTML and PDF

Most functionalities in kableExtra can work in both HTML and PDF. In fact, as long as you specifies format in kable() (which can be set globally through option knitr.table.format), functions in this package will pick the right way to manipulate the table be themselves. As a result, if users want to left align the table, kable(...) %>% kable_styling(position = "left") will work in both HTML and PDF. Recently, we also introduced a new kbl() function acting as an alternative to kable but provides better documentation and format detection.

Install

install.packages("kableExtra")

# For dev version
devtools::install_github("haozhu233/kableExtra")

Basic Usage

library(kableExtra)
dt <- mtcars[1:5, 1:4]

# HTML table
kbl(dt, caption = "Demo Table") %>%
  kable_styling(bootstrap_options = "striped",
                full_width = F) %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2[note]" = 2)) %>%
  footnote(c("table footnote"))

# LaTeX Table
kbl(dt, booktabs = T, caption = "Demo Table") %>%
  kable_styling(latex_options = c("striped", "hold_position"),
                full_width = F) %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2[note]" = 2)) %>%
  footnote(c("table footnote"))

Results

More Information

For more information, please check the package vignette.

Acknowledgement

I would like to thank colleagues at Hebrew SeniorLife Marcus Institute for Aging Research and the Boston Pepper Center for their input. I also would like to appreciate the mentorship from Tom Travison (@tgt75) and all the efforts from the open source community, which help this package keep getting better.

kableextra's People

Contributors

antaldaniel avatar aschersleben avatar aukustifm avatar bsalzer avatar cjber avatar danchaltiel avatar dmurdoch avatar georgegui avatar ghaarsma avatar haozhu233 avatar iago-pssjd avatar isteves avatar jiaxiangbu avatar jjchern avatar jokorn avatar kbrevoort avatar krlmlr avatar kupietz avatar michaelchirico avatar penkiln avatar quocpeyrot avatar salim-b avatar samiaab1990 avatar steffilazerte avatar stlagsk avatar t-kalinowski avatar tbates avatar tomjemmett avatar vincentarelbundock avatar wibeasley avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kableextra's Issues

Error when installing the package

When I try to install the package I get the following errors related to the URL not being found, lib not specified and telling me kableExtra is not available for my current R version.

Could you help?

install.packages("kableExtra")
Warning in install.packages :
cannot open URL 'http://www.stats.ox.ac.uk/pub/RWin/src/contrib/PACKAGES.rds': HTTP status was '404 Not Found'
Installing package into ‘C:/Users/2151521/Documents/R/win-library/3.4’
(as ‘lib’ is unspecified)
Warning in install.packages :
package ‘kableExtra’ is not available (for R version 3.4.0)

group_rows() fails on tables featuring values in scientific notation

If table cells contain values >=1 in scientific notation, group_rows() fails.

library(knitr)
library(kableExtra)

df1 =
  data.frame(
    a = 1:5,
    b = formatC(seq(5, 1, -1), format = 'e', digits = 1)
  )

df2 =
  data.frame(
    a = 1:5,
    b = formatC(seq(5, 1, -1)*0.1, format = 'e', digits = 1)
  )

# this fails
df1 %>% kable(format = 'latex') %>% kable_styling() %>% group_rows('Group 1', 1, 5)
\begin{table}[!h]
\centering
\begin{tabular}{r|l}
\hline
a & b\\
\hline
1 & 5.0e+00\\
\hline
2 & 4.0e+00\\
\hline
3 & 3.0e+00\\
\hline
4 & 2.0e+00\\
\hline
5 & 1.0e+00\\
\hline
\end{tabular}
\end{table}
# this works
df2 %>% kable(format = 'latex') %>% kable_styling() %>% group_rows('Group 1', 1, 5)
\begin{table}[!h]
\centering
\begin{tabular}{r|l}
\hline
a & b\\
\hline
\multicolumn{2}{l}{\textbf{Group 1}}\\
\hline
\hspace{1em}1 & 5.0e-01\\
\hline
\hspace{1em}2 & 4.0e-01\\
\hline
\hspace{1em}3 & 3.0e-01\\
\hline
\hspace{1em}4 & 2.0e-01\\
\hline
\hspace{1em}5 & 1.0e-01\\
\hline
\end{tabular}
\end{table}

This is likely due to a parsing error when a plus sign ('+') is present in the table.

df3 =
  data.frame(
    a = 1:5,
    b = rep('-', 5)
  )

df4 =
  data.frame(
    a = 1:5,
    b = rep('+', 5)
  )

# this works
df3 %>% kable(format = 'latex') %>% kable_styling() %>% group_rows('Group 1', 1, 5)
\begin{table}[!h]
\centering
\begin{tabular}{r|l}
\hline
a & b\\
\hline
\multicolumn{2}{l}{\textbf{Group 1}}\\
\hline
\hspace{1em}1 & -\\
\hline
\hspace{1em}2 & -\\
\hline
\hspace{1em}3 & -\\
\hline
\hspace{1em}4 & -\\
\hline
\hspace{1em}5 & -\\
\hline
\end{tabular}
\end{table}
# this fails
df4 %>% kable(format = 'latex') %>% kable_styling() %>% group_rows('Group 1', 1, 5)
\begin{table}[!h]
\centering
\begin{tabular}{r|l}
\hline
a & b\\
\hline
\multicolumn{2}{l}{\textbf{Group 1}}\\
\hline
\hspace{1em}1 & +++\\
\hline
\hspace{1em}2 & ++\\
\hline
\hspace{1em}3 & ++\\
\hline
\hspace{1em}4 & ++\\
\hline
\hspace{1em}5 & ++\\
\hline
\end{tabular}
\end{table}

Ability to create borders for columns (similar to align in xtable)

In xtable we can use align to add column borders with a | pipe:

xtable(latex_xtable_outliers, align = "rrll|llr|r")

Regardless of the alignment, (#26), I think the border is very important and currently missing from kable and pander.

I know kableExtra does something similar with the add_header_above, but that forces us to write a column group name, and for some reason (html related) I don't always get the borders visible.
Also if I leave a blank name in add_header_above, it does not do the grouping anymore.

Is what I am asking for even doable, given that it's html?

Thanks

column_spec width fails

Thanks for this awesome package.

Am generating latex tables with knitr::kable and kableExtra as part of a Bookdown project.

I have a two column table, with long text in the second column:

library(tidyverse)
library(knitr)
library(kableExtra)

table1 <- tribble(~Term, ~Definition,
                         "Adverse event (AE)", " Any untoward medical occurrence in a subject to whom a medicinal product has been administered including occurrences which are not necessarily caused by or related to that product.",
                         "Adverse reaction (AR)", "Any untoward and unintended response in a subject to an investigational medicinal product, which is related to any dose administered to that subject.",
                         "Unexpected adverse reaction (UAR)", " An adverse reaction the nature and severity of which is not consistent with the information about the medicinal product in question set out in: The SPC for that product (for products with a marketing authorisation); The Investigator's Brochure (IB) relating to the trial in question (for any other investigational product)",
                         "Serious adverse event (SAE); Serious adverse reaction (SAR); Suspected unexpected serious adverse reaction (SUSAR)", "Respectively, any adverse event, adverse reaction or unexpected adverse reaction that: results in death; is life-threatening; requires hospitalisation or prolongation of existing hospitalisation; results in persistent or significant disability or incapacity; consists of a congenital anomaly or birth defect; other important medical event(s)"
)

When I try to specify the width of the second column, it fails.

knitr::kable(table1, caption = "Terms and definitions for adverse events", booktabs=TRUE) %>%
  kable_styling(full_width=F, latex_options = "scale_down") %>%
  column_spec(column = 2, width = "30em")

with the following message:

! Use of \@array doesn't match its definition.
\new@ifnextchar ...served@d = #1\def \reserved@a {
                                                  #2}\def \reserved@b {#3}\f...
l.1133 \end{tabular}}

Very grateful for any suggestions for resolving.

kable_styling not respecting html tags in cells

After applying kable_styling html tags inside cells are not being respected.

E.g. this is one of my cell entries

&bull; Review ANOVA vocabulary <br> &bull; Read up on the [final project instructions](../Projects/ProjectPage.html).

Neither the bullet points, nor the line break tags are rending. The link however works just fine.

\caption{} instead of \caption[]{} has the caption repeated in list of tables for each page

With the fix for the multiply definition of \label in #25 I see we have another issue, which was actually the reason I opened #25.

With \listoftables in latex we have repeated entries for each page the table appears on, e.g.

this list of tables . . . . . . . . . . . . . . . . . . . . . . . 192
this list of tables (cont) . . . . . . . . . . . . . . . . . . . 202
this list of tables (cont) . . . . . . . . . . . . . . . . . . . 212
this list of tables (cont) . . . . . . . . . . . . . . . . . . . 222
this list of tables (cont) . . . . . . . . . . . . . . . . . . . 232

Changing \caption{} to \caption[]{} would only list the first caption.
Unsure whether this warrants an option.

Group_rows not working properly for longer latex table

Hello!

I'm really liking your package, but have run into an issue when trying to group by rows in a slightly longer latex table. When using the group_rows on a row starting on row 17 or beyond, this has no effect on the table when knitting to pdf, i.e. the table is produced as if that line of code didn't exist. It works perfectly fine when knitting to HTML.

The code I'm using looks like this, and I've tried both the CRAN-version and the github version of the kableExtra package.

library(knitr)
library(kableExtra)

kable(marginal$table, caption = "Table 1", booktabs = T, align = "c") %>%
  kable_styling() %>%
  group_rows("Other data", 11, 16) %>%
  group_rows("Our data", 17, 22)

Copy README material to package documentation

You have a nice narrative in the repo's readme file. Consider copying some of that to the documentation. Specifically the page dedicated to the entire package. I was about to start that, but I didn't want it to look like I wrote the material.

If you don't want to maintain duplicated material, maybe include a link (from the doc to the readme).

I sometimes forget that nonvocal majority of R users know only CRAN, and not CRAN+GitHub. A few days ago, I was recommending your package (to an analyst who works in a bank). His institution currently blocks access to all of GitHub (including the normal website). For people like that, the CRAN documentation is their only real option.

kable_styling(full_width = T) doesn't work for tables with a caption

I am getting an error for setting kable_styling(full_width = T) when combined with caption parameter from 'kable' itself. I'm trying to render a pdf with 'knitr'.

Example:
1. basic table, this works fine

library(kable)
library(kableExtra)
kable(mtcars[1:5, 1:5],
      format = "latex",
      booktabs = TRUE) %>%
  kable_styling(full_width = TRUE)

image

2. When a caption has been set this gives an error

kable(mtcars[1:5, 1:5],
      format = "latex",
      caption = "A caption",
      booktabs = TRUE) %>%
  kable_styling(full_width = TRUE)

output:

! Package array Error:  Illegal pream-token (t): `c' used.

add_header_left for other formats

Hi, it looks like add_header_left() is implemented for html and latex in your dev version. Do you plan on extending it to other formats?

Thanks!

Knit to Word

Hello!
So far I love kableExtra for HTML tables. For me, it would be really useful to have features like add_indent available for knitting to Word documents as well. Do you plan to add support for knitting to Word documents in the future? Thanks!

Missing footnotes when aligning tables in dev version

I'm raising this issue in relation to this question on SO that you answered for me:

https://stackoverflow.com/questions/45378664/kableextra-rmarkdown-tables-aligning-grouping-row-labels-and-footnotes

I put an update of the problem in a comment but figured it would be easier for you to look at here. Basically now alignment of grouping rows works in the dev version, but the footnote text has disappeared totally rather than being aligned incorrectly. Not sure why this is happening as the superscript footnote numbers still appear in the table, it's just the footnote text itself that has disappeared.

A further fix would be appreciated, if possible!

Here is the code to reproduce the error:

library(devtools)
dev_mode(on = T)
install_github("haozhu233/kableExtra")

library(kableExtra)
library(knitr)

#' ### Example table

#' **Note that the actual text of footnotes is missing**

#+ cars-table, results='asis'
kable(mtcars[1:10, 1:2], format = "html", caption = "Group Rows", 
      col.names = c("MPG[note]", "CYL[note]")) %>%
    kable_styling("striped", full_width = F) %>%
    group_rows("Group 1", 4, 7) %>%
    group_rows("Group 2", 8, 10) %>% 
    add_footnote(c("Some footnote", "Some other footnote"))

dev_mode(on = F)

kableExtra with latex package in yaml

Here is a minimal example:

---
title: "Untitled"
output:
  bookdown::pdf_book: default
header-includes:
  - \usepackage{tocloft}  
---

\renewcommand{\cftfigfont}{Figure }


```{r cars}
library(knitr)
library(kableExtra)
usepackage_latex('tocloft')
dt <- mtcars[1:5, 1:6]

options(knitr.table.format = "latex")

kable(dt,booktabs = T) %>%
   kable_styling(latex_options = c("striped", "hold_position"), full_width = T)

If not loading the latex package tocloft manually using usepackage_latex('tocloft'), knitting the file will throw the following error, even I do load tocloft in yaml via header-includes.

! LaTeX Error: \cftfigfont undefined.

Error: Failed to compile Untitled.tex. See Untitled.log for more info.
Execution halted

header-includes in yaml works fine if not using kableExtra.

Problem with "["-bracket in data, if using collapse_rows()

There is a problem using collapse rows, if [ is in the data. Here are two examples. One with [ and one without [:

library(dplyr)
library(knitr)
library(kableExtra)

test <- tibble(A1=c(rep("A",3),"B"),A2=c("a","[","c","d"))
test2 <-tibble(A1=c(rep("A",3),"B"),A2=c("a","b","c","d"))

kable(test, booktabs=TRUE, format="latex") %>% collapse_rows(1)

kable(test2, booktabs=TRUE, format="latex") %>% collapse_rows(1)

and the results:

grafik

Problem with german "Umlaute" UTF-8 for example ä or ü in Latex using kable_styling

Hello,

i have problems with using kable_styling from kableExtra and german "Umlaute" in Latex. I use:
test <- kable(tbldf, format="latex", booktabs=TRUE, caption="Test") %>%
kable_styling(latex_options=c("striped","scale down"))

The result shows this, with the wrong german "Umlaute":

"\rowcolors{2}{gray!6}{white}\n\begin{table}\n\n\caption{\label{tab:}hallo}\n\centering\n\resizebox{\linewidth}{!}{\begin{tabular}[t]{lllllll}\n\hiderowcolors\n\toprule\nunbeb & 2011 & 2012 & 2013 & 2014 & 2015 & 2016\\\n\midrule\n\showrowcolors\nindividuelle Bauweise & 87 & 77 & 95 & 101 & 60 & 127\\\nGeschosswohnungsbau & 29 & 26 & 49 & 29 & 45 & 36\\\nklassisches Gewerbe & 10 & 18 & 22 & 13 & 13 & 11\\\nterti攼㸴res Gewerbe & 25 & 12 & 4 & 9 & 4 & 5\\\nNichtbauland & 126 & 108 & 91 & 122 & 103 & 93\\\nSumme unbebaute Grundst昼㹣cke & 277 & 241 & 261 & 274 & 225 & 272\\\n\bottomrule\n\end{tabular}}\n\end{table}\n\rowcolors{2}{white}{white}"
attr(,"format")
[1] "latex"
attr(,"class")
[1] "knit_asis"
attr(,"kable_meta")
attr(,"kable_meta")$tabular
[1] "tabular"

attr(,"kable_meta")$booktabs
[1] TRUE

attr(,"kable_meta")$align
[1] "lllllll"

Is there a solution for this???

Peter Rath

loading kableExtra breaks inline R code in YAML header

I've been using a YAML header in my R markdown document (*.Rmd) that inserts headers and footers. My left footer uses inline R code to display the path and filename of the PDF file that will result when the file is knitted in R studio. I discovered today that loading the kableExtra package breaks that inline code and causes the code itself to display rather than the result of the code. Commenting out the library(kableExtra) line in the code below corrects the footer to show the path instead of the inline code that supposed to generate it.

Code for reproducing the problem is below.

---
output:
  pdf_document:
    latex_engine: xelatex
header-includes:
- \usepackage{fancyhdr}
- \usepackage[yyyymmdd,hhmmss]{datetime}
- \usepackage{lastpage}
- \usepackage{fontspec}
- \pagestyle{fancy}
- \lhead{Left header}
- \rhead{\today\ \currenttime}
- \cfoot{ }
- \fancyfoot[RE,RO]{\thepage\ of \pageref*{LastPage}}
- \renewcommand{\headrulewidth}{0.4pt}
- \renewcommand{\footrulewidth}{0.4pt}
- \fancypagestyle{plain}{\pagestyle{fancy}}
- \lfoot{\texttt{\small \detokenize{`r sub(".Rmd", ".pdf", knitr:::current_input(dir=TRUE))`}}}
---

# Setup 
``` {r global_options}
# Global chunk options (must be a stand-alone initial R chunk). 
knitr::opts_chunk$set(include  = TRUE, echo = TRUE, error = TRUE, 
                      message = TRUE, warning = TRUE)
library(knitr)            # for kable().
library(kableExtra)       # For formatting tables made by kable().

% bug, continued

Hi again,

I was hit by the % bug. I downloaded the dev-version yesterday, and it worked in one of my tables. A table using booktabs and an added extra header row.

However, in the second table where I also grouped rows, it was only possible to use '%' in one column! As soon I added percent values in more than one column the grouping disappeared.

/hans

option striped destroys the UTF-8 characters

Hello,

Look:

> dat <- data.frame(A="a", B="µ")
> library(kableExtra)
> options(knitr.table.format = "latex")
> kable(dat) %>% kable_styling(latex_options = c("striped"))
\begin{table}[!h]
\centering\rowcolors{2}{gray!6}{white}

\begin{tabular}{l|l}
\hiderowcolors
\hline
A & B\\
\hline
\showrowcolors
a & �\\
\hline
\end{tabular}
\rowcolors{2}{white}{white}
\end{table}

Print from HTML (Webpage) to PDF loses coloring?

This may not be your issue but I figured I'd ask. When I try to print from an HTML webpage to a PDF I am unable to maintain the coloring of text (all black) or background coloring within the table itself.

for example: in the webpage the following code turns the first row of the table yellow.

row_spec(1, background = "yellow")

However, when I go to PDF the page in Chrome, FF, & IE they all do not maintain the background coloring. Any ideas? (I've been Googling all day).

Thanks!

LaTeX math expression in group of columns header

Hello,

The kable function has an option escape which allows to have LaTeX math expressions in the table - see https://stackoverflow.com/questions/45391566/latex-math-expression-in-knitr-kable-sweave

Is it possible to have a LaTeX math expression in the header of some grouped columns ? I'm afraid no, currently.

\documentclass{article}
\usepackage{booktabs}
\begin{document}

<<>>=
library(knitr)
library(kableExtra)
dat <- mtcars[1:5,1:5]
options(knitr.table.format = "latex")
@

<<results='asis'>>=
names(dat)[1] <- "$x^2$"
kable(dat, booktabs = TRUE, caption = "My table", escape = FALSE) %>% 
  add_header_above(c("", "", "$x^3$" = 4))
@

\end{document}

capture

bookdown, short.caption (kable) is not compatible with font.size (kableExtra), ! LaTeX Error: Not in outer par mode.

I am getting an error for setting font size parameter in kable_styling function when combined with short.caption parameter from kable itself. I need to use short.caption for list of tables. The error is
! LaTeX Error: Not in outer par mode.

It seems like the short.caption is causing extra "table" environment inserted in tex document.

https://gist.github.com/ivanek/d58158006992c5e9c7251d3a1bdad049

`column_spec` producing compilation error in latex pdf

Hi,

Thanks for this awesome package! I found a problem when using the kableExtra::column_spec function both with my own data frame and the example in the LaTeX vignette of the package. I'm using knit and editing my Rnw file in emacs with ESS.

The document will not compile unless the package array is in the preamble of the Rnw file. Despite the same occurs with the booktabs package that is needed for the knitr::kable function's argument booktabs to work, but I found no mention of the array package both in the vignette and the function manual. I suggest to include somewhere a list of the latex packages that would be potentially needed for the document to compile smoothly. This is just a suggestion but think that such move will improve greatly the user experience.

Thanks again,

Gustavo

let landscape() cache (or warn) \usepackage{lscape} \usepackage{pdflscape} insertions

I'm a happy user of landscape(), but I ran into a slight snafu on repeated builds with cache, and I have a theory as to why this happened.

Observation

Only on cached (via knitr) compilations, the LaTeX compilation would fail with something like landscape environment undefined.

Deleting the cache, or setting the chunk with landscape() option cache = FALSE resolved the problem.

Our project, at this point, had no \usepackage{lscape}or \usepackage{pdflscape} in its preamble.tex.

Hypothesis

I am assuming that when landscape() is called, kableExtra does some black magic to insert the necessary usepackage{lscape} and friends into the preamble.
This, however, would be a side effect that wouldn't (couldn't) be cached.
Whenever the offending chunk is unchanged, a repeated run will leave the chunk unevaluated and knitr will simply reuse the old outputs, of course without the side effects.

On all n>=1 runs without changed chunks, then, black magic never happens and \usepackage{lscape} and friends are never appended, causing a failed compilation.

Solution

I don't know, I like the idea of not manually calling usepackage{lscape}, but these side effects are thorny to debug.
This may be hard for other users to recognise (I have some painful experience with caching).

Perhaps warn users about this, or simply not do the black magic, but ask users to manually add the packages?

(cc @VerenaKasztantowicz)

kableExtra incompatible with \usepackage{fancyhdr}?

Hi,
I was really thrilled when I found kableExtra and managed to produce some fancy tables. However, when I copied the code into my markdown report I lost some other features in the document instead.

I had previously managed to configure headers and footers with the 'fancyhdr' package (see the added lines below). But as soon as I includes 'library(kableExtra)' the headers and footers disappear. Any idea about the incompatability?

/hans

header-includes:

  • \usepackage{fancyhdr}
  • \pagestyle{fancyplain}
  • \fancyfoot[LE,RO]{\thepage}
  • \rhead{\includegraphics[height=2cm]{slu.png}}

collapse_rows() doesn't end up with vertically centred entry

Hi!

I have the following example. It results in a table, where car 1 is to be found somewhere in the 4th fifth of the vertical distribution, rather than directly in the middle. This creates for more complex tables and longer values in this "collapsed cell" rather strange behaviour and sometimes the text even crosses the lower boundary of the group. It seems almost as if the value would be centred between the two maximum border of the table per page, and not between the two borders of the group that should be collapsed.

---
documentclass: book
lof: no
lot: no
output:
  bookdown::pdf_book:
    fig_caption: yes
    keep_tex: yes
    number_sections: yes
  bookdown::html_document2:
    fig_caption: yes
    theme: spacelab
subtitle: null
---
library(knitr)
library(magrittr)
library(bookdown)
library(captioner)
library(stringr)
library(dplyr)
library(kableExtra)
long_dt <- cbind(car = row.names(mtcars), mtcars)
rownames(long_dt) <- NULL
long_dt[,1] <- c(rep("car 1", 22), rep("car 2", 10))

kable(long_dt, 
      longtable = T,
      format = "latex",
      booktabs = T, 
      caption.short = "An awesome \\textsc{Longtable}.",
      caption = "An awesome Longtable, with a caption.") %>%
  add_header_above(c(" ", "Group 1" = 5, "Group 2" = 6)) %>%
  kable_styling(latex_options = "repeat_header") %>%
  collapse_rows(columns = 1)

Even more strangely, if you set the line long_dt[,1] <- c(rep("car 1", 22), rep("car 2", 10)) to long_dt[,1] <- c(rep("car 1", 16), rep("car 2", 16)), car 2 is printed where the repeated header on the second page would be printed otherwise.

If I compile it to html it works without problems.

[Feat. req] Grouping rows the same way like headers

Hi,

you did awesome work! But why did you implement two different ways to group rows and cols?
I need to group the rows not just once. Like "add_header_above" I need to group the goups again.

Wouldn't it be more consistent to implement a function like "add_rowgroup_left"?

Maybe I did just miss how to do it? Is there a way to group the rows in multiple layers?

Best,
kn1g

row_spec?

I don't see row_spec as part of KableExtra package...

\bottomrule at the end of longtable can cause an issue with option repeat_header

Hello,

LaTeX issue described here: https://tex.stackexchange.com/questions/384576/longtable-starts-a-second-page-to-print-only-the-bottomrule-line

kableExtra (or kable?) generates this code:

......
Maserati Bora & 15.0 & 8 & 301.0 & 335 & 3.54 & 3.570 & 14.60 & 0 & 1 & 5 & 8\\
Volvo 142E & 21.4 & 4 & 121.0 & 109 & 4.11 & 2.780 & 18.60 & 1 & 1 & 4 & 2\\
\bottomrule
\end{longtable}

The issue is fixed by removing \bottomrule and replacing \endhead with

\endhead
\bottomrule
\endfoot

what about a cell_spec ?

What about having a cell_spec function which allowed you to alter the bold/colour etc of an individual cell in the table ?

Even better, would be great if we could pass it a formula which printed all failures in red or bold for example. (i.e., if any cells are <9, then print in red).

styling seems to break with kable()'s 'caption.short'

A while ago knitr supported a short caption for the list of tables, please see yihui/knitr#1199.

I am not 100% sure if this is an issue of kableExtra, but it seems so, because when I have a kable (including a short caption) and then attempt to use kable_styling() even without any options set, I get a latex-error "Not in outer par mode".

Looking at the *.tex file reveals with kable_styling

\begin{table}[!h]
\centering\begin{table}

\caption[short caption]{long caption}
\centering
\begin{tabular}[t]{lllll}
\toprule
...

in contrast to

\begin{table}

\caption[short caption]{long caption}
\centering
\begin{tabular}[t]{lllll}
\toprule
...

without kable_styling. Can you reproduce this? Or did I mess up setting something properly?

Latex code in header won't work with kableExtra

Hi.

I have a dataframe where I have inserted latex code for bold:
\textbf{92}

and where I am using some latex code in the header:
print(kable(newpercentages, caption="Percentage of readings $\\geq$ $^{\\circ}$C", etc ...

It works in plain kable (I get the correct latex symbols in the header, and the value '92' comes out in bold), but when I use kableExtra the latex code is not interpreted, and I see the raw latex code in the table.

Have I missed something obvious or is this not possible with kableExtra ?

Pete

Bug of striped table when there are two sets of grouped columns

Hello,
The Rnw file below produces an unexpected result.

\documentclass[table]{article}
\usepackage{longtable}
\usepackage{booktabs}
\usepackage{xcolor}

\begin{document}

<<>>=
library(knitr)
library(kableExtra)
options(knitr.table.format = "latex")
dat <- rbind(mtcars, mtcars)
@

<<results='asis'>>=
kable(dat, booktabs=TRUE, longtable=TRUE, 
      caption="A long striped table") %>%
  add_header_above(c(" ", "Group" = 5, " ", "Other Group" = 5)) %>%
  kable_styling(latex_options = c("striped", "repeat_header"))
@

\end{document}

There are two problems. Firstly, the second line of the header on the first page is colored:

capture1

Secondly, on the second page the caption and the first line of the header are colored:

capture2

Below is the generated LaTeX code:

\rowcolors{2}{white}{gray!6}

\begin{longtable}[t]{lrrrrrrrrrrr}
\caption{\label{tab:unnamed-chunk-2}A long striped table}\\
\toprule
\multicolumn{1}{c}{ } & \multicolumn{5}{c}{Group} & \multicolumn{1}{c}{ } & \multicolumn{5}{c}{Other Group} \\
\cmidrule(l{2pt}r{2pt}){2-6} \cmidrule(l{2pt}r{2pt}){8-12}
  & mpg & cyl & disp & hp & drat & wt & qsec & vs & am & gear & carb\\
\midrule
\endfirsthead
\caption{\label{tab:unnamed-chunk-2}A long striped table \textit{(continued)}}\\
\toprule
\multicolumn{1}{c}{ } & \multicolumn{5}{c}{Group} & \multicolumn{1}{c}{ } & \multicolumn{5}{c}{Other Group} \\
\cmidrule(l{2pt}r{2pt}){2-6} \cmidrule(l{2pt}r{2pt}){8-12}
  & mpg & cyl & disp & hp & drat & wt & qsec & vs & am & gear & carb\\
\midrule
\endhead
Mazda RX4 & 21.0 & 6 & 160.0 & 110 & 3.90 & 2.620 & 16.46 & 0 & 1 & 4 & 4\\
Mazda RX4 Wag & 21.0 & 6 & 160.0 & 110 & 3.90 & 2.875 & 17.02 & 0 & 1 & 4 & 4\\
Datsun 710 & 22.8 & 4 & 108.0 & 93 & 3.85 & 2.320 & 18.61 & 1 & 1 & 4 & 1\\
Hornet 4 Drive & 21.4 & 6 & 258.0 & 110 & 3.08 & 3.215 & 19.44 & 1 & 0 & 3 & 1\\
Hornet Sportabout & 18.7 & 8 & 360.0 & 175 & 3.15 & 3.440 & 17.02 & 0 & 0 & 3 & 2\\
\addlinespace
Valiant & 18.1 & 6 & 225.0 & 105 & 2.76 & 3.460 & 20.22 & 1 & 0 & 3 & 1\\
Duster 360 & 14.3 & 8 & 360.0 & 245 & 3.21 & 3.570 & 15.84 & 0 & 0 & 3 & 4\\

Long footnote text causes striped row backgrounds and change in column alignment

This is issue is linked to #31.

When running the code below, the long footnote spans over more than one line, and so gets the striped background. It also then changes the alignment of the column on the far right.

Is there a way to allow long footnotes to spread over more than one line whilst maintaining alignment of columns and with a non-striped background?

Demo .Rmd code, using the dev version of kableExtra:

knitr::opts_chunk$set(echo = TRUE)
options(knitr.table.format = "latex")
library(knitr)
library(kableExtra)
dt <- cbind(mtcars[1:5, 1:6], mtcars[1:5, 1:6])

kable(dt, caption = "Demo Table[note]", booktabs = T) %>%
kable_styling(latex_options = c("striped", "hold_position")) %>%
add_header_above(c(" ", "Group 1[note]" = 3, "Group 2[note]" = 3)) %>%
add_footnote(c("This table is from mtcars. Lots more text to make the footnote nice and long. Even more text. And a bit more. That's enough.",
"Group 1 contains mpg, cyl and disp.",
"Group 2 contains hp, drat and wt."),
notation = "symbol")

striped_foonote_rows

how to remove begin{tabular} ?

Hello,

thanks for this amazing package.

I use it to export dataframes to latex tables that I can include in my tex. However, I was unable to only get the fragment of the table, that is the latex output without the \begin{tabular} environment (because I use my own).

Is there a way to get rid of these lines using kableExtra ?

Thanks!

add tabularx environment instead of kable_styling(full_width = T) ?

Hello @haozhu233 !

I tried to use the nice kable_styling(full_width = T) option to stretch my latex table but the result is unfortunately quite disappointing in terms prettyness.

Would it be possible to add some option where the table is actually written in a tabularx environment? That will naturally handle the stretching beautifully.

What do you think?
Thanks!

bug when longtable starts at the top of a page

Hello,

This is the Rnw file:

\documentclass{article}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage[table]{xcolor}
\usepackage{lipsum}
\begin{document}

<<setup, include=FALSE>>=
library(knitr)
opts_chunk$set(echo=FALSE)
library(kableExtra)
options(knitr.table.format = "latex")
dat <- mtcars
@

\lipsum[3-6]

a

b

c

d

e

f

g

<<results='asis'>>=
kable(dat, booktabs = TRUE, longtable = TRUE, caption = "My table") %>%
  kable_styling(latex_options = c("repeat_header", "striped")) 
@

\end{document}

And the output:

capture

Do you have an idea ? Otherwise I can open an issue on texstackexchange. I will firstly search if this issue is a known one.

add_header_rows skips when colspan=1

Perhaps I do not understand the point of add_header_rows, but I would like to do the following:

require(dplyr)
require(knitr)
require(kableExtra)
nro <- 2
data.frame(x1=rnorm(nro),x2=rnorm(nro),y1=runif(nro)) %>%
  knitr::kable(format='html') %>%
  kableExtra::add_header_above(header=c('x'=2,'y'=1))

However, what I get out is:

x
x1 x2 y1
0.7999 -0.0302 0.3919
-1.1490 0.9670 0.1744

Where is the y? The problem seems to arise in htmlTable_new_header_generator, where I see:

        if (x[2] == 1 | trimws(x[1]) == "") {
            paste0("<th style=\"border-bottom:hidden\"></th>")
        }

Perhaps the | should be an &?

add_header_above appearing below colnames

Hello I am trying to recreate an example in the vignette and I am having some trouble. The columns names are appearing above the add_head_above characters instead of below. Here is the code I am running and my session info. I am also running it in rstudio and using the knit button

library(knitr)
library(kableExtra)
library(methods)

options(knitr.table.format = "html") 


dt <- mtcars[1:5, 1:6]
kable(dt) %>%
  kable_styling("striped") %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2" = 2, "Group 3" = 2)) 
sessionInfo()
## R version 3.2.3 (2015-12-10)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: CentOS release 6.9 (Final)
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
##  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
## 
## attached base packages:
## [1] graphics  grDevices utils     datasets  stats     methods   base     
## 
## other attached packages:
## [1] kableExtra_0.2.1.9000 knitr_1.16            survival_2.40-2      
## [4] rlocal_4.2.0          arsenal_0.4.2        
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_0.12.11    xml2_1.0.0      magrittr_1.5    splines_3.2.3  
##  [5] rvest_0.3.2     lattice_0.20-34 R6_2.2.1        highr_0.6      
##  [9] stringr_1.2.0   httr_1.2.1      tools_3.2.3     grid_3.2.3     
## [13] htmltools_0.3.6 yaml_2.1.14     rprojroot_1.2   digest_0.6.12  
## [17] tibble_1.3.0    Matrix_1.2-7.1  readr_1.0.0     evaluate_0.10  
## [21] rmarkdown_1.5   stringi_1.1.5   backports_1.0.3

Thanks for any help you can provide!

Yellow Highlight a Row?

First off, this package is seriously amazing. Thank you so very much for building it.

Q: Is there a way to yellow highlight a row? it seems that row_spec() only allows for bold and italics?

Repeat header in longtable repeats the \label from ktable()

When using repeat_header I get latex warnings about the table's label being multiply defined.

This appears to stem from knitr::kable adding the environments' label inside its table_info$caption, which kableExtra copies when repeating the header.

I wonder whether there is any workaround?

Solution could probably be instead of adding "cont." or individual repeat_header_text to the end of the caption-string to require the user to set repeat_header_text to be the full caption again (as does longtable when manually constructing it via \endfirsthead and friends.)

This would add more flexibility and remove the label-repetition but might break currently expected behavior. Maybe check whether repeat_header_text is set, otherwise add (cont.).

New Features in kableExtra 0.2.0 & 0.2.1

There are a few interesting new features introduced in kableExtra 0.2.0 & 0.2.1. Version 0.2.0 is on CRAN now but 0.2.1 is still under review (they might reject this submission because it was submitted a day after 0.2.0. Ops :P).

  • group_rows()
    This is the row version of add_header_above() even though the syntax is a little different. Basically, you can group several rows of the table under a chunk label.
  • add_indent()
    This function will add a 2em indentations to the first column of selected rows. It's actually called internally by group_rows but I feel like it's useful by itself as well.
  • column_spec()
    You can define column width, font bold & font italic for selected column. It's useful when you have long paragraph of explanatory texts in your table cells but the automate arrangement failed to fulfill its duty
  • landscape()
    This function is for LaTeX only and it will put the table on an isolated landscape page.

For more details and examples, you can see the doc site: http://haozhu233.github.io/kableExtra/
I have updated the docs and the new features are in the end.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.