R markdown: how to print dataframe compactly - r

I am using knitr::kable to print my dataframes, but sometimes they are too big. Is there any simple way to print them compactly with scrollbar?
For example, I do:
knitr::kable(mtcars)
How could I add scrolling by condition (for example, if nrow > 10 and/or ncol > 10)?
P.S. DT::datatable doesn't work for big ncol:
I need exactly scrolling interface.

You can add scrollbars. For example, with kableExtra or DT:
R Markdown
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(kableExtra)
```
Some very wide data:
```{r}
df <- cbind(mtcars, mtcars)
```
With `kableExtra`:
```{r}
kable(df) %>%
kable_styling("striped", full_width = F) %>%
scroll_box(width = "100%", height = "200px")
```
Or with `DT`:
```{r}
DT::datatable(
df,
height = 200,
options = list(scrollX = TRUE)
)
```
output

Related

Set internal document link as table value in Rmarkdown

I would like to set each value of a column in a datatable as an internal link to a different slide. Below is what I have tried but the link is not selectable.
---
title: "Example"
output: slidy_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r message=FALSE, warning=FALSE, include=FALSE}
library(DT)
library(tidyverse)
```
## Table
```{r carstab, echo = FALSE}
datatable(mtcars %>% rownames_to_column(var = "plot") %>% mutate(plot = ("[plot](#/plot)")),escape = TRUE)
```
## plot
```{r plot, echo = TRUE}
plot(mtcars)
```
mutate(plot = ("[plot](#/plot)")) does not work because the markdown code [plot](#/plot) will not be translated to HTML. Its a character.
You want something like <a href = '#(slide_number)'> This is a link </a> in your DT cells.
You could generate such links using paste0():
datatable(
mtcars %>%
mutate(
plot = 3,
plot = paste0("<a href = '#(", plot, ")'>link</a>"),
), escape = FALSE
)
The plot column in your DT now contains valid links to slide 3 (modify the first instance of plot in mutate() accordingly to link to different slides).

Kable (kableExtra) vertical scrollbar in knitted RMarkdown html_document?

The vertical scrollbar generated with kableExtra works in RStudio but doesn't work in the knitted html_document.
Example
Take the following Rmd file
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
library(dplyr)
library(kableExtra)
```
```{r}
iris %>%
kable %>%
kable_styling("striped", full_width = F)
```
When running the chunk in RStudio, I see a vertical scrollbar
But after knitting, the vertical scrollbar is gone and the whole data.frame is printed
How can I get the vertical scrollbar to display in the knitted HTML the same as it was in RStudio?
Have a look at the function scroll_box() from the package kableExtra.
```{r}
iris %>%
kable %>%
kable_styling("striped", full_width = F) %>%
scroll_box(width = "500px", height = "200px")
```
To specify the size of the box, see the arguments in the documentation

how to automatically rename columns with math mode?

Consider this simple example
---
title: "Untitled"
output:
pdf_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
options(knitr.table.format = "latex")
```
## Slide with R Output
```{r , echo = FALSE ,warning = FALSE}
library(knitr)
library(kableExtra)
library(dplyr)
cars %>%
filter(dist < 5) %>%
kable('latex', booktabs = T, escape = F, col.names = c( "$\\alpha$" , "$\\beta$" ) ) %>%
kable_styling(latex_options = c("striped", "hold_position"),
full_width = T)
```
Now this correcly generates the following output
The issue is that the renaming in col.names is manual and very tedious when my dataframe has many columns.
I would like to be able to able to say " if you see this variable dist in the dataframe, then map it to $\alpha$. Otherwise leave as is.
How can this be done?
Note, I am rendering the file using rmarkdown::render()
Thanks!!

For Loop for Creating Multiple Tables using knitr and kableExtra packages in RMarkdown

I need to create multiple tables in RMarkdown and style it with the kableExtra package. As an example, I have the iris dataset. My first table displays the first 20 rows, my second table the next 20 rows, and my third table next 20 rows... Below is the code:
---
title: ""
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
library(knitr)
library(kableExtra)
landscape(kable_styling(kable(iris[1:20, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T))
landscape(kable_styling(kable(iris[21:40, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T))
landscape(kable_styling(kable(iris[41:60, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T))
```
It works well and it returns three tables, each one in a different sheet. In reality I have more than just three tables so I thought it would be a lot wiser to use a for loop and I made use of the answer given in this link R: why kable doesn't print inside a for loop?. Simple I put a line break after each print call as advised.
---
title: "untitled"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
library(knitr)
library(kableExtra)
for (i in 1:3) {
print(landscape(kable_styling(
kable(iris[20*(i-1)+1:20*i, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T)))
cat("\n")
}
```
But it does not work. I guess that is because I encapsulated the kable command with the commands from the kableExtra package.
Is there who can make it work? I mean is there a way that can save me from typing?
Your existing code was nearly there. I think the only change needed is to add results='asis' to the chunk option (I don't think the extra newline is necessary). Here's the full RMarkdown content which works for me
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r results='asis'}
library(knitr)
library(kableExtra)
for (i in 1:3) {
print(landscape(kable_styling(
kable(iris[20*(i-1)+1:20*i, ], format = "latex", align = "c",
row.names = FALSE), latex_options = c("striped"), full_width = T)))
}
```

How to fit large frequency table into R markdown ioslides?

I'm trying to fit large table of frequencies into my slide. There are many values, and even the rare ones would be nice to show.
I played with different options but none gives me a satisfactory solution. Here is Rmd so far:
---
title: "Untitled"
author: "author"
date: "date"
output: ioslides_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
df <- as.data.frame(table(rownames((USArrests))))
```
## table 1
```{r t1, echo = TRUE}
table(rownames((USArrests)))
```
## table 2
```{r t2}
library(knitr)
library(kableExtra)
kable(df, "html") %>%
kable_styling(bootstrap_options = "striped", font_size = 10)
```
Table 1 doesn't fit:
Table 2 could be squeezed but with tiny font, and lots of wasted space on the sides.
I also looked into pander, xtable and stargazer but failed to find solution from them either.
Any other alternatives?
You could spread your table across multiple columns to fit the space. In my example below, I split the frame up into 3 pairs of columns with uneven length.
---
output: ioslides_presentation
---
```{r setup, include=FALSE}
library(dplyr)
library(magrittr)
library(knitr)
library(kableExtra)
```
## table 1
```{r, echo=TRUE, eval=FALSE}
USArrests %>% rownames %>% table
```
```{r, echo=FALSE}
df <- USArrests %>%
rownames %>%
table %>%
as_tibble
df %$%
tibble(
name1 = `.`[1:17],
n1 = n[1:17],
name2 = `.`[18:34],
n2 = n[18:34],
name3 = c(`.`[35:50], ""),
n3 = c(n[35:50], "")
) %>%
kable("html", align = c("l", "c"), col.names = rep(c("Name", "Frequency"), 3)) %>%
kable_styling(bootstrap_options = c("striped", "condensed"), font_size = 18)
```
N.B. I accept the transform step into multiple columns could have been done more elegantly and providing and more programmatic solution, however, I'll leave that to others to refine.

Resources