Migwell
Migwell

Reputation: 20117

Limit column width for paged rmarkdown tables

Let's say I have an Rmarkdown document. In that document, I create an data frame with two columns, and each of them is quite long. Also I have the "paged" output setting.

---
title: "Long Tables"
output:
  html_document:
    toc: true
    toc_depth: 3
    df_print: paged
---

```{r}
alphabet = paste(LETTERS, letters, collapse = "", sep = "")
data.frame(
    a = rep(alphabet, 10),
    b = rep(alphabet, 10)
)

When I knit this to HTML, it appears like this:

enter image description here

It is important that I can get both columns to fit on screen without the user having to click through to each column. Ideally there would be an rmarkdown setting to solve this. If not, is there a way to actually truncate the columns behind the scenes, but without actually showing the user the code that is doing the truncation? Because this will complicate the example that I am demonstrating in the document.

Upvotes: 3

Views: 1151

Answers (2)

Quinten
Quinten

Reputation: 41275

A different solution is setting the style (CSS) for the table. This means that you can determine your own width of the table. So this code is behind the scenes, because when you open the html, you actually don't see the CSS code. You can use the following code:

---
title: "Long Tables"
output:
  html_document:
    toc: true
    toc_depth: 3
    df_print: paged
---

<div style="width = 100%">
```{r}
alphabet = paste(LETTERS, letters, collapse = "", sep = "")
df <- data.frame(
    a = rep(alphabet, 10),
    b = rep(alphabet, 10)
)
DT::datatable(df)
```
</div>

Output looks like this:

enter image description here

Upvotes: 0

manro
manro

Reputation: 3677

Try this solution:

Your data:

```{r, echo=FALSE}
alphabet = paste(LETTERS, letters, collapse = "", sep = "")
df <- data.frame(
       a = rep(alphabet, 10),
       b = rep(alphabet, 10)
)
```

Your table:

```{r, echo=FALSE, warning=FALSE}
library(DT)
datatable(df, extensions = 'FixedColumns')
```

P.S. How to customize your table further - you can find a lot of interesting info there

enter image description here

Upvotes: 1

Related Questions