Search code examples
rhyperlinkhtml-tabler-markdownrnotebook

R Notebook HTML Format - add hyperlinks to paged table


I wish to knit an html file from an R Notebook that contains paged tables with hyperlinks.
Hyperlinks can be inserted using knitr::kable, but I can't find a way to generate a paged table with this function.
Paged tables are the default notebook output, but I can't find a way of inserting functional hyperlinks. Many thanks for your help.

---
title: "Paged notebook table with hyperlinks"
output:
  html_notebook:
    code_folding: "hide"
---

```{r rows.print=3}
wiki.url <- "https://en.wikipedia.org/wiki/"
df1 <- data.frame(Month=month.name, URL=paste0("[", month.name, "](", wiki.url, month.name, ")"))
df2 <- data.frame(Month=month.name, URL=paste0("<a href='", wiki.url, month.name, "'>", month.name, "</a>"))
print(df1)
```

```{r rows.print=3}
print(df2)
```

```{r rows.print=3}
knitr::kable(df1)
```

```{r rows.print=3}
knitr::kable(df2)
```

Solution

  • Since there doesn't seem to be a perfect solution to my problem, I thought I'd post the workaround that I came up with - in case someone has a similar problem.
    I created the table plus hyperlinks with knitr::kable and then added an html button and inline javascript to toggle visibility - not as elegant as a paged table, but does the job.
    Note the <script> tag at the bottom of the file that hides tables by default.
    (Paste code into an .Rmd file in RStudio):

    ---
    title: "Managing large tables with hyperlinks in html notebook"
    output:
      html_notebook:
        code_folding: "hide"
    ---
    
    <script>
    function myFunction(id) {
        var x = document.getElementById(id);
        if (x.style.display === 'none') {
            x.style.display = 'block';
        } else {
            x.style.display = 'none';
        }
    }
    </script>
    
    ```{r}
    library(knitr)
    df1 <- data.frame(Month=month.name, Link=paste0("[", month.name, "](https://en.wikipedia.org/wiki/", month.name, ")"))
    ```
    
    <button class="button" onclick="myFunction('DIV_months')">Show/hide table</button>
    <div id="DIV_months" class="div_default_hide">
    ```{r}
    knitr::kable(df1)
    ```
    </div>
    
    <script>
    var divsToHide = document.getElementsByClassName("div_default_hide");
    for(var i = 0; i < divsToHide.length; i++)
        {
        divsToHide[i].style.display = 'none';
        }
    </script>