Search code examples
rr-markdowngt

Add link to gt table elements without additional text


I want to add links to my gt table cells as shown:

raw_dat <- mtcars[1:15, ] %>% rownames_to_column(var = "id") %>% select(id, mpg)
tibble(
  name = raw_dat$id,
  link = paste(raw_dat$mpg, "And <a href = 'https://www.cars.com//'>here</a>")) %>%
  mutate(link = map(link, gt::html)) %>%
  gt

Results:

enter image description here

How can I make the link fall on the raw_dat$mpg and not have any additional text after it. So the desired output is by clicking on the raw_dat$mpg cell, you can be taken to cars.com.


Solution

  • You can use the following code:

    library(dplyr)
    library(gt)
    raw_dat <- mtcars[1:15, ] %>% rownames_to_column(var = "id") %>% select(id, mpg)
    df <- tibble(
      name = raw_dat$id,
      link =  'https://www.cars.com//')
    
    df %>%
      mutate(link = sprintf('<p><a href = "%s">%s</a>', link, raw_dat$mpg),
             link = map(link, gt::html)) %>%
      gt
    

    Output:

    enter image description here