I want co change column width in pdf with kable ( , 'latex') but the fucntion doesn't work. Anybody know why? here is my code:
table = knitr::kable(jeden, "latex" , row.names = F , align = "llrrrrrrrrrr" , escape = F, booktabs = F, caption = '1. Sprzedaz uslug i towarow razem')
kableExtra::column_spec(table, 1, width = "1cm", bold = TRUE, italic = TRUE)
It's not a bug but rather a relatively strange setting for align in knitr::kable(). In xtable you can put align in a string but for kable, you will have to provide a vector. In your case, if you put things like align = c(rep("l", 2), rep("r"), 2), you should be fine.
It seems that align breaks your column_spec, but only for LaTeX/PDF output.
Here are two minimal & reproducible examples.
PDF output
---
title: "Untitled"
output:
pdf_document: default
---
```{r}
library(knitr)
library(kableExtra)
x <- kable(head(mtcars[, 1:4]), "latex", row.names = F, align = "llrr")
column_spec(x, 1:2, width = "4cm", bold = TRUE, italic = TRUE)
```
If you remove align from the PDF RMarkdown document, column_spec works as expected.
HTML output
---
title: "Untitled"
output:
html_document: default
---
```{r}
library(knitr)
library(kableExtra)
x <- kable(head(mtcars[, 1:4]), "html", row.names = F, align = "llrr")
column_spec(x, 1:2, width = "4cm", bold = TRUE, italic = TRUE)
```
This seems like a bug to me, and I would suggest opening an issue on the kableExtra GitHub site. If you do, you should reference this post, and include a minimal & reproducible example (similar to what I did).
Related
I've created a table in RMarkdwon (PDF) with the knitr and kableExtra packages.
I can choose in the kable-function between left,center or right- alignments.
But I want that the content of the table cells are aligned to the decimal points.
In this case it is difficult since there are asterisks behind the numbers indicating the significance.
Here is a reproduceable example:
library(tidyverse)
library(knitr)
library(kableExtra)
tribble(
~Variable_1,~Variable_2,
"13.5","4.4**",
"12.7***","1.2*",
"0.4","0.3***",
"2.3**","11.5**"
)%>%
kable(format = "latex", booktabs=T, escape = T)%>%
kable_styling(position = "center", latex_options = "hold_position")
Which produces this table:
Can someone give me an easy solution directly in R?
If this should not be possible, how would an edit in the latex code look like?
Many thanks in advance!
Here is the table provided by bttomio:
One solution could be intersing the variable names in {} recommended by https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf page 28.
The code then looks like this:
tribble(
~Variable_1,~Variable_2,
"13.5","4.4**",
"12.7***","1.2*",
"0.4","0.3***",
"2.3**","11.5**"
)%>%
rename_all( ~ str_c("{ ",.," }"))%>%
kable(format = "latex", booktabs=T, escape = T)%>%
kable_styling(position = "center", latex_options = "hold_position")
And the table corresponds to the desired output:
But the problem is the full-width-option in the kable_styling-function. If I set this option to TRUE the linebreak of large column names disappears.
Here is a first try:
---
output: pdf_document
header-includes:
- '\usepackage{siunitx}'
- '\newcolumntype{d}{S[table-format=3.2]}'
---
```{r}
library(tidyverse)
library(knitr)
library(kableExtra)
tribble(
~Variable_1,~Variable_2,
"13.5","4.4**",
"12.7***","1.2*",
"0.4","0.3***",
"2.3**","11.5**"
)%>%
kable(format = "latex", booktabs=T, escape = T, align = "d")%>%
kable_styling(position = "center", latex_options = "hold_position")
```
Here I give a reproducible example in RMarkdown.
---
title: "A reproducible example in rmarkdown"
output: html_document
---
<script>
$(document).ready(function(){
$('[data-toggle="popover"]').popover();
});
</script>
```{r}
library(tidyverse)
library(kableExtra)
df = tibble(
position = c("top", "bottom"),
latex = c("$x=1$", "$x=2$"),
pop = cell_spec(
paste("Math", latex),
popover = spec_popover(
content = latex,
title = NULL,
position = position
)
),
) %>%
select(-latex)
df %>% kbl(escape = F)
```
The popover message shows the row latex code as $x=1$ and $x=2$, but not as latex math equation. How could one get the equations typeset as math equations?
I am attempting to generate a PDF from a Bookdown script which includes a complex table. The table includes some parameter names that have subscripts in them. I would also like to colour some of the rows. An example script is shown below:
---
title: "Example problem"
author: "Frida Gomam"
site: bookdown::bookdown_site
documentclass: book
output:
#bookdown::gitbook: default
bookdown::pdf_book: default
always_allow_html: yes
---
This is a test example for the problem.
```{r}
library(magrittr)
library(knitr)
library(kableExtra)
df <- data.frame(Parameter = c("NO~x~ emissions", "SO~2~ emissions", "CO~2~ emissions"), "Value mg/Nm^3^" = c(800,900,1000),check.names=F)
knitr::kable(df,escape = F, caption = 'Example table!', booktabs = TRUE, format = "latex") %>% #
row_spec(0, bold = T, color = "white", background = "#045a8d") %>%
row_spec(c(2), bold = T, color = "white", background = "#3690c0")
```
blah blah
I can run the script using the kable format as 'format = "html"' and the result looks fine including the coloured rows and subscripts. When I change the format to Latex, the subscripts are not displayed properly in the produced pdf.
I have tried adding the argument escape = F to kable, but the build process fails.
Quitting from lines 14-23 (_main.Rmd)
Error in kable_latex(x = c("$NO_{x}$ emissions", "SO2 emissions", "CO2 emissions", :
unused argument (example = FALSE)
Calls: <Anonymous> ... eval -> %>% -> eval -> eval -> <Anonymous> -> do.call
Can anyone help solve this problem?
For me it works if I use (escaped) LaTeX syntax:
---
title: "Example problem"
author: "Frida Gomam"
site: bookdown::bookdown_site
documentclass: book
output:
bookdown::pdf_book: default
#bookdown::gitbook: default
always_allow_html: yes
---
This is a test example for the problem.
```{r}
library(magrittr)
library(knitr)
library(kableExtra)
df <- data.frame(Parameter = c("NO\\textsubscript{x} emissions", "SO\\textsubscript{2} emissions", "CO\\textsubscript{2} emissions"),
"Value mg/Nm\\textsuperscript{3}" = c(800,900,1000),
check.names = F)
knitr::kable(df,escape = F, caption = 'Example table!', booktabs = TRUE, format = "latex") %>% #
row_spec(0, bold = T, color = "white", background = "#045a8d") %>%
row_spec(c(2), bold = T, color = "white", background = "#3690c0")
```
blah blah
I'm generating GIFs using the gganimate package within an RMarkdown file. When using output = github_document in the front matter, the GIF appears as expected in the output (github-document-output). However, when using output = html_document, the GIF generates with alt text, which defaults to the chunk name (html-document-output).
Is there a way to suppress this automatic caption? I've tried setting my own caption using the fig.cap chunk option, but that was unsuccessful.
RMarkdown code
---
output:
html_document: default
github_document: default
---
```{r}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "output/test-fig-",
cache.path = "output/test-cache-"
)
```
```{r cache = FALSE}
library(knitr)
library(animation)
ani.options(autobrowse = FALSE, interval = 1)
opts_knit$set(animation.fun = function(x, options, format = "gif") {
x = c(knitr:::sans_ext(x), knitr:::file_ext(x))
fig.num = options$fig.num
format = sub("^[.]", "", format)
fig.fname = paste0(sub(paste0(fig.num, "$"), "*", x[1]),
".", x[2])
mov.fname = paste0(sub(paste0(fig.num, "$"), "", x[1]), ".",
format)
# order correctly
figs <- Sys.glob(fig.fname)
figs <- figs[order(as.numeric(stringr::str_match(figs, paste0("(\\d+)\\.", x[2]))[, 2]))]
animation::im.convert(figs, output = mov.fname)
sprintf("![%s](%s)", options$label, paste0(opts_knit$get("base.url"), mov.fname))
})
opts_chunk$set(cache = TRUE, message = FALSE, warning = FALSE, fig.show = "animate")
```
```{r pkgs, cache = FALSE}
library(gapminder)
library(ggplot2)
theme_set(theme_bw())
```
```{r setup}
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent, frame = year)) +
geom_point() +
scale_x_log10()
```
```{r dependson = "setup"}
library(gganimate)
gg_animate(p)
```
The problem here is that you include the resulting animation with markdown syntax. This introduces some iiritations I guess.
Taking a look at hook_plot_html we can simulate the default output for standard plots:
sprintf(paste0('<div class="figure %s">',
'<img src="%s">',
'<p class="caption">%s</p>',
'</div>'), options$fig.align, mov.fname, options$fig.cap)
I'm trying to produce table to a Latex-pdf document. I'm using kableExtra and knitr in R.
I have a table that has long column names. When I rotate the header row by 90 degrees linebreaks won't work. Does anyone have an idea how I could achieve both rotated row and linebreaks?
My example is the same as in Hao's Best Practice for newline in Latex table, but I added piped row_spec to the end of the code.
\documentclass[10pt,a4paper]{article}
\usepackage[table]{xcolor}
\begin{document}
\begin{table}
<<global_options, echo=FALSE>>=
library(kableExtra)
library("dplyr")
dt_lb <- data.frame(
Item = c("Hello\nWorld", "This\nis a cat"),
Value = c(10, 100)
)
dt_lb %>%
mutate_all(linebreak) %>%
kable("latex", booktabs = T, escape = F,
col.names = linebreak(c("Item\n(Name)", "Value\n(Number)"))) %>%
row_spec(0, angle = 90, align='l', monospace=T)
#
\end{table}
\end{document}
What I get is this, but the [l] tags hint that there's something else wrong with the tags as well:
On StackExchange TEX I found a question about rotation and linebreaks, this is what I'm trying achieve: https://tex.stackexchange.com/questions/14730/big-table-with-rotated-column-labels-using-booktabs
You could use tableHTML:
library(tableHTML)
Replace the new line character "\n" with the HTML tag <br>:
headers <- c("Item\n(Name)", "Value\n(Number)") %>%
stringr::str_replace_all(pattern = "\\n", replacement = "<br>")
Create a tableHTML object and rotate the headers using add_css_header():
dt_lb %>%
tableHTML(rownames = FALSE,
headers = headers,
escape = FALSE,
widths = c(100, 100),
theme = 'scientific') %>%
add_css_header(css = list(c('transform', 'height', 'text-align'),
c('rotate(-45deg)', '70px', 'center')),
headers = 1:2)
The result looks like this:
Note: you can add more css or default themes. Check out the vignettes for more details:
If you want to create a pdf document, you could use RMarkdown:
---
title: "tableHTML2pdf"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
\
```{r}
library(tableHTML)
dt_lb <- data.frame(
Item = c("Hello\nWorld", "This\nis a cat"),
Value = c(10, 100)
)
headers <- c("Item\n(Name)", "Value\n(Number)") %>%
stringr::str_replace_all(pattern = "\\n", replacement = "<br>")
dt_lb %>%
tableHTML(rownames = FALSE,
headers = headers,
escape = FALSE,
widths = c(100, 100),
theme = 'scientific') %>%
add_css_header(css = list(c('transform', 'height', 'text-align'),
c('rotate(-45deg)', '70px', 'center')),
headers = 1:2)
```
\
It will then create an HTML file. This file can then be converted to PDF using wkhtmltopdf.
I think you probably rendered your rmarkdown document into HTML... In the rmarkdown yaml header, does it say html_document right now? If so, you can try to change it to pdf_document.....
I rendered a pdf_document with exactly the same code and I think I got what you were looking for...
---
title: "Table Sample"
output: pdf_document
---
``` {r, include = FALSE}
library(tidyverse)
library(kableExtra)
```
```{r}
dt_lb <- data.frame(
Item = c("Hello\nWorld", "This\nis a cat"),
Value = c(10, 100)
)
dt_lb %>%
mutate_all(linebreak) %>%
kable("latex", booktabs = T, escape = F,
col.names = linebreak(c("Item\n(Name)", "Value\n(Number)"), align = "c")) %>%
row_spec(0, angle = 90)
```
Latex package makecell was missing.
Hao pointed out that Page 3 of this manual lists some of the necessary Latex packages: haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf