Search code examples
rfilepathgt

How can I create the correct path to create images in a gt table


I want to include images of country flags in a table created by the gt R package

library(tibble)
library(gt)

df <- tibble(country = c("Italy","Wales"), 
             flag = c("images/flags/Italy.png","images/flags/Wales.png")
             )

# example with hardcoded country
df %>% 
  gt() %>%
  text_transform(
    locations = cells_body(vars(flag)),
    fn = function(x) {
      country = "Wales"
      local_image(
        filename = paste0("images/flags/",country,".png")
    )
    }
  )

Hardcoding in the country into this code produces an output - but obviously always repeats the same flag irrespective of the value of the country column

So I am looking the correct way to replace "Wales" with some reference to the vars(country) of the same row

TIA


Solution

  • I'm sorry, but I don't get your question because you seem to have the path already in your data frame? However, how about the following

    BASE.PATH <- "images/flags/"
    IMG.TYPE <- ".png"
    
    
    df <- data.frame(
      country = c("Italy","Wales"))
    
    
    create.path <- function(row) {
      path <- paste(BASE.PATH, row["country"], IMG.TYPE, sep = "")
      return(path)
    }
    
    df$image.path <- apply(df, 1, create.path)
    
    
    load.country.image <- function(row) {
      my.image <- my.load.logic(row["image.path"])
      return(my.image)
    }
    
    df$image <- apply(df, 1, load.country.image)
    

    This dynamically creates the path for you, and loads the image. You only have to change load.country.image according to your needs. My guess is

    load.country.image <- function(row) {
      country.image <- local_image(filename = row["image.path"])
      return(country.image)
    }
    

    I hope this helps!

    PS: Can you please clarify, if this is not what you are looking? Thank you!

    EDIT If you want to use tibble and gt, the following should work on your computer as it does on mine.

    library(tibble)
    library(gt)
    
    df <- tibble(country = c("Italy","Wales"), 
                 flag.path = c("images/flags/Italy.png","images/flags/Wales.png"))
    
    
    df %>% 
      gt() %>%
      text_transform(
        locations = cells_body(vars(flag.path)),
        fn = function(flag.path) {
          #  The key is here.
          lapply(flag.path, local_image)
        }
      )
    

    The key to the problem is to understand that text_transform passes the locations column/row as a whole to fn. In other words, flag.path is just a vector.