Search code examples
rhtml-tabler-markdown

How to keep a selection of column/rows while scrolling columns and rows on a rmarkdown HTML table?


The goal is to imitate the "freeze columns and rows in Excel" in an HTML table within an RMardown document.

Here is an example:

---
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
rmarkdown::paged_table(mtcars)
```

The ouput is a HTML document with this table:

enter image description here

When you click on "Next", to scroll rows, it keeps the column names on top of the table:

enter image description here

However, when you click on the triangle symbol on the right of the column names, to scroll the columns, the rownames disapear:

enter image description here

1. How to keep rownames while scrolling columns?

2. How to choose the row(s)/column(s) kept while scrolling?

I was not able to find this option in knitr::kable(), rmarkdown::paged_table() nor flextable, am I missing something?


Solution

  • Answer to the first question

    you can use FixedColumns extension of DataTable (i.e. using the {DT} package) to fix the row names (1st column) while scrolling horizontally.

    ---
    title: "fixed columns"
    output: html_document
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    ```
    
    ```{r}
    DT::datatable(
      mtcars, 
      extensions = 'FixedColumns',
      options = list(
        dom = 't',
        scrollX = TRUE,
        fixedColumns = TRUE
      )
    )
    ```