I'm working a report with rmarkdown and latex. I need to print a group of tables using knitr::kable, but the don't print when inside a for loop.
This is my code:
---
title: "project title"
author: "Mr. Author"
date: "2016-08-30"
output:
pdf_document:
latex_engine: xelatex
bibliography: biblio.bib
header-includes:
- \usepackage{tcolorbox}
---
Text and chunks that run ok.
```{r loadLibraries}
require(data.table)
require(knitr)
```
## Try to print a group of tables from split
```{r results = "asis"}
t1 <- data.table(a = sample(letters, 10, T), b = sample(LETTERS[1:3], 10, T))
t2 <- split(t1, t1$b)
for (i in 1:length(t2)){
kable(t2[[i]], col.names = c("A", "B"))
}
```
It doesn't matter if I use results = "asis" or if I omit it altogether, nothing prints to the document.
I've tried enclosing the kable call within a print call (print(kable(t2[[i]]...), and it successfully prints the output to the document, but the format is the same format as a standard R prompt (preceded by ##, for example), which is rather ugly.
How can I display the tables, other than manually?
### EDIT ###
Some answerers have redirected me to R knitr print in a loop as a duplicate answer. It's not, because as I stated in the previous paragraph, this effectively prints the table, but the format is not the expected one. The accepted answer (and related github thread) really solved the problem.
This question is addressed here: https://github.com/yihui/knitr/issues/886
All you need is a line break after each print call
---
title: "project title"
author: "Mr. Author"
date: "2016-08-30"
output:
pdf_document:
latex_engine: xelatex
bibliography: biblio.bib
header-includes:
- \usepackage{tcolorbox}
---
Text and chunks that run ok.
```{r loadLibraries}
require(data.table)
require(knitr)
```
```{r results = "asis"}
t1 <- data.table(a = sample(letters, 10, T), b = sample(LETTERS[1:3], 10, T))
t2 <- split(t1, t1$b)
for (i in 1:length(t2)){
print(kable(t2[[i]], col.names = c("A", "B")))
cat("\n")
}
```
Related
I am trying generate automated reports using rmarkdown, and final output expected is pdf. However, when I run the script the resulting .Rmd file is okay, but the resulting .pdf file does not show the table. It just shows the table as a list of values. However, if I open the .Rmd file in RStudio, and use the kint button, I get a correctly formatted pdf file. Has anyone seen this behaviour before? am I missing something?
---
title: "RUO"
author: "Me"
date: "`r format(Sys.Date(), '%B %d, %Y')`"
always_allow_html: true
output:
pdf_document:
df_print: kable
keep_tex: true
latex_engine: lualatex
header-includes:
- \usepackage{graphicx}
- \usepackage{fancyhdr}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage[para,flushleft]{threeparttable}
- \usepackage{fontspec}
- \setmainfont{Raleway}
- \AtBeginDocument{\let\maketitle\relax}
classoption:
- twocolumn
---
\fancypagestyle{plain}{}
\pagestyle{fancy}
\addtolength{\headheight}{1.0cm}
\rhead{Name: John Doe\\Sex: Male\\DoB: 01.01.01\\Lab \#: XXXXXXXX\\MRN \#: XXXXXXXX}
```{r setup, warning = FALSE, message = FALSE, echo = FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
library(tidyverse)
library(stringi)
library(DESeq2)
library(kableExtra)
```
## This section is for Research Use Only
### Expression Table
```{r ExpTable}
df <- data.frame(cbind("gene_name" = c("AAA", "BBB", "CCC"),
"z-score" = c(-2, 2, 3)))
df %>%
setNames(c("Gene Name", "Z-score")) %>%
as.data.frame() %>%
# as_tibble() %>%
knitr::kable(booktabs = T) %>%
kableExtra::kable_styling(latex_options = c("hold_position", "striped")) # %>%
# kableExtra::column_spec(2, width = "3 cm")
```
\vfill
### Methodology
Some Description
### Comments and Limitations
Disclosures.
\clearpage
This code is the minimal example. When you use something like:
Rscript -e "library('knitr'); knitr::knit('filename.Rmd')"
The table does not render, but opening the same file in RStudio, renders is correctly.
UPDATE:
I realized after some more digging, that this is a un-reported bug (probably). If you render a rmarkdown with a table to pdf, then it will usually render correctly. But sometimes, the table is rendered as a list in the first render, and if you then render the same .Rmd to pdf, the table is rendered and correctly reformatted. So if you render the same file twice, the second time all the tables are correctly rendered. This happens more frequently if the only thing your file has a single table.
Good morning everybody,
as stated above, I’m trying to render multiple Rmarkdown reports with different parameters for each report. Basically I have a folder of .csv files, which I have to clean up. I have packed all the steps in an .Rmd file, because this way the data gets cleaned and a short report is generated documenting the results. Some figures, some stats, nothing very dramatic, just an overview of how the cleaning went.
As each .csv file is slightly different, I have to tweak some parameters. This is the easy part. I have found some nice code in the “R for Data Science” book, which you can find here. https://r4ds.had.co.nz/r-markdown.html#parameters
This is my version:
library(dplyr)
library(stringr)
library(purrr)
# Create a vector with names
files <- c("dataframe", "datatable")
# Create a tibble with filenames and lists of parameters
reports <- tibble(
filename = str_c(files, ".html"),
params = map(files, ~ list(name = .,
factor = if_else(. == "dataframe", 2.5, 5))))
#-------------------------------------------------------------------
# make reports
reports <- reports %>%
select(output_file = filename, params) %>%
purrr::pwalk(rmarkdown::render, input = "template_datatable.Rmd")
Everything runs fine, when the .Rmd file uses data.frames.
As my .csv are about 1 GB each, I would use data.table to speed things up. But as soon as my .Rmd file contains some data.table code I get this error message:
Error: `:=` can only be used within a quasiquoted argument
If I just render one file with rmarkdown::render(input = "template_datatable.Rmd", output_file = "test.html", params = list(name = "datatable", carat = 5)), the .Rmd with the data.table code works fine.
My questions are.
What is causing this error? And is there a way to fix it?
Here is my code for the .Rmd using data.frames:
---
title: "A report for `r params$name`"
params:
name: "name"
factor: 1
output:
bookdown::html_document2:
fig_caption: yes
toc: yes
toc_float: true
code_folding: "hide"
---
```{r setup, include=FALSE}
# Setup Chunk
# Some knitr options
knitr::opts_chunk$set(echo = FALSE)
# Packages
library(dplyr)
library(ggplot2)
```
```{r dataImport}
df <- data.frame(A = seq(1, 100), B = seq(1, 100))
df <- df %>%
mutate(C = B * params$factor)
```
```{r makePlot}
ggplot(df, aes(A, C)) +
geom_line()
```
And my code for the .Rmd using data.tables:
```
---
title: "A report for `r params$name`"
params:
name: "name"
factor: 1
output:
bookdown::html_document2:
fig_caption: yes
toc: yes
toc_float: true
code_folding: "hide"
---
```{r setup, include=FALSE}
# Setup Chunk
# Some knitr options
knitr::opts_chunk$set(echo = FALSE)
# Packages
library(data.table)
library(ggplot2)
```
```{r dataImport}
dt <- data.table(A = seq(1, 100), B = seq(1, 100))
dt <- dt[, C := B*params$factor]
```
```{r makePlot}
ggplot(dt, aes(A, C)) +
geom_line()
```
Thanks for your help.
Similar to how to create a loop that includes both a code chunk and text with knitr in R i try to get text and a Code snippet created by a Loop.
Something along this:
---
title: Sample
output: html_document
params:
test_data: list("x <- 2", "x <- 4")
---
for(nr in 1:3){
cat(paste0("## Heading ", nr))
```{r, results='asis', eval = FALSE, echo = TRUE}
params$test_data[[nr]]
```
}
Expected Output would be:
What i tried:
I tried to follow: https://stackoverflow.com/a/36381976/8538074. But printing "```" did not work for me.
You can make use of knitr hooks. Take the following MRE:
---
title: "Untitled"
output: html_document
params:
test_data: c("x <- 2", "x <- 4")
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, results = 'asis', echo = F}
hook <- knitr::hooks_html()$source
opts <- knitr::opts_chunk$get()
chunks <- eval(parse(text = params$test_data))
for(nr in seq_along(chunks)){
cat(paste0("## Heading ", nr, "\n"))
cat(hook(chunks[nr], options = opts))
}
```
We get the default source hook and also the default chunk options. Then we get the test data, which is supplied as a string. Therefore we parse and evaluate that string.
In the loop we simply call the source hook on each element of the test data. Here is the result:
When I embed a table generated by using knitr::kable,
I want to adjust the width of the table in beamer_presentation's slide.
Like this picture, some columns don't show in slide when executing the following codes.
Could you tell me how to solve this problem without changing column's names?
---
title: "test"
author: "test"
date: "`r Sys.time()`"
output:
beamer_presentation:
latex_engine: xelatex
fontsize: 6pt
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
knitr::opts_chunk$set(warning = FALSE)
knitr::opts_chunk$set(include = FALSE)
library(tidyverse)
library(kableExtra)
library(knitr)
```
## Table
```{r test, results = "asis",include=TRUE}
test_tbl = tibble(
example_name1 = c("a", "b"),
example_name2 = c("aa", "bb"),
example_name3 = c("aaa", "bbb"),
example_name4 = c("aaaa", "bbbb"),
example_name5 = c("aaaaa", "bbbbb")
)
knitr::kable(test_tbl, format = "markdown")
```
The table is too large to fit on one slide. By adjusting the font size with kableExtra the size of the table can be changed. To do this, set the argument format = "latex" in kable() and then pipe kable_styling().
knitr::kable(test_tbl, format = "latex") %>%
kableExtra::kable_styling(font_size = 7)
It is useful to include LaTeX packages like booktabs to format tables nicely with kable or kableExtra. This is not as flexible as working with LaTeX directly but often leads to quite good results.
First of all, include booktabs in the YAML header.
---
title: "test"
author: "test"
date: "`r Sys.time()`"
header-includes:
- \usepackage{booktabs}
output: beamer_presentation
---
Then set booktabs = TRUE in kable().
knitr::kable(test_tbl, format = "latex", booktabs = T) %>%
kableExtra::kable_styling(font_size = 7)
Say I'd like to display a table of coefficients from several equations in an R Markdown file (html output).
I'd like the table to look somewhat like this:
But I can't for the life of me figure out how to tell R Markdown to parse the column names in the table.
The closest I've gotten is a hacky solution using cat to print custom table from my data.frame... not ideal. Is there a better way to do this?
Here's how I created the image above, saving my file as an .Rmd in RStudio.
---
title: "Math in R Markdown tables"
output:
html_notebook: default
html_document: default
---
My fancy table
```{r, echo=FALSE, include=TRUE, results="asis"}
# Make data.frame
mathy.df <- data.frame(site = c("A", "B"),
b0 = c(3, 4),
BA = c(1, 2))
# Do terrible things to print it properly
cat("Site|$\\beta_0$|$\\beta_A$")
cat("\n")
cat("----|---------|---------\n")
for (i in 1:nrow(mathy.df)){
cat(as.character(mathy.df[i,"site"]), "|",
mathy.df[i,"b0"], "|",
mathy.df[i,"BA"],
"\n", sep = "")
}
```
You can use kable() and its escape option to format math notation (see this answer to a related question). Then you assign your mathy headings as the column names, and there you go:
---
title: "Math in R Markdown tables"
output:
html_notebook: default
html_document: default
---
My fancy table
```{r, echo=FALSE, include=TRUE, results="asis"}
library(knitr)
mathy.df <- data.frame(site = c("A", "B"),
b0 = c(3, 4),
BA = c(1, 2))
colnames(mathy.df) <- c("Site", "$\\beta_0$", "$\\beta_A$")
kable(mathy.df, escape=FALSE)
```