Search code examples
rr-markdownformattergt

How to pass more than one parameter to a gt table formatter


In the example below which I found here [https://community.rstudio.com/t/create-interactive-links-in-gt-table-in-rmarkdown/70266/3][1]

the formatter function takes the url as parameter coming from um column and use the link itself as the text for the link, I've been trying to pass a second parameter where the text for the link would come from another column, "name" for instance, how can I achieve that?

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

```{r}
library(gt)

make_hyperlink = function(myurl,mytext=myurl) {
  paste('<a href="',myurl,'">',mytext,'</a>')
}

df <- data.frame(
  stringsAsFactors = FALSE,
           country = c("UK", "US"),
              name = c("BBC", "CNN"),
              link = c("https://www.bbc.com/news", "https://edition.cnn.com/")
)

df %>%
gt() %>%
  fmt (
    columns = 'link',
    fns = make_hyperlink
  )


  [1]: https://community.rstudio.com/t/create-interactive-links-in-gt-table-in-rmarkdown/70266/3

Solution

  • You can use htmltools::HTML -

    library(dplyr)
    library(gt)
    
    df %>%
      mutate(link = make_hyperlink(link, name)) %>%
      gt() %>%
      fmt (
        columns = 'link',
        fns = function(x) sapply(x, htmltools::HTML)
      )
    

    enter image description here