Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add vertical lines to tables produced with R knitr::kable in pdf?

I want to produce a table with knitr::kable with vertical lines on the borders and between certain columns. Is there a way to do it? My output document is pdf.

Thanks!

like image 435
iago Avatar asked Jun 17 '19 08:06

iago


People also ask

What does the Kable function do in R?

The kable() function in knitr is a very simple table generator, and is simple by design. It only generates tables for strictly rectangular data such as matrices and data frames. You cannot heavily format the table cells or merge cells.

How do I add a line to a table in R?

To add or insert observation/row to an existing Data Frame in R, we use rbind() function. We can add single or multiple observations/rows to a Data Frame in R using rbind() function.

What is Kable package in R?

Function 'kable()' is a light weight table generator coming from 'knitr'. This package simplifies the way to manipulate the HTML or 'LaTeX' codes generated by 'kable()' and allows users to construct complex tables and customize styles using a readable syntax.


2 Answers

Not too much clear, but maybe this could help:

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

dt <- mtcars[1:5, 1:6]
dt %>% 
kable() %>%
# here you can add the vertical line, in my example, for all the columns
column_spec (1:7,border_left = T, border_right = T) %>%
kable_styling()

enter image description here

And if you need to save it as .pdf:

save_kable(k, "k.pdf")

With k as the result of the code above.

like image 169
s__ Avatar answered Oct 30 '22 09:10

s__


Answer using huxtable:

library(huxtable)
library(dplyr)

as_hux(mtcars[1:5, 1:6], add_colnames = TRUE) %>%
      set_right_border(2:5, everywhere, 0.4) %>%
      set_bottom_border(1, everywhere, 0.4)

You can then save it to PDF with quick_pdf(), or print it within a rmarkdown document.

like image 30
dash2 Avatar answered Oct 30 '22 09:10

dash2