Home > database >  Add link to gt table elements without additional text
Add link to gt table elements without additional text

Time:06-09

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.

CodePudding user response:

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

CodePudding user response:

Perhaps you can construct a string using sprintf (not tested, obviously).

link = sprintf("<a href = 'https://www.cars.com'>%s</a>", raw_dat$mpg)

CodePudding user response:

Taking together both existing solution. Here is a straight tidyverse approach:

library(tidyverse)
library(gt)

mtcars %>% 
  slice(1:15) %>% 
  rownames_to_column("name") %>% 
  mutate(link =  'https://www.cars.com//',
         link = sprintf('<p><a href = "%s">%s</a>', link, raw_dat$mpg),
         link = map(link, gt::html)) %>%
  select(name, link) %>% 
  gt

enter image description here

..... .....

  • Related