Search code examples
rgt

programmatically pass cell value to title in GT tab_header


I would like to use the value in a specific column as the title for my gt table.
All rows in the title column have the same character value.
How do I reference a column in tab_header

I want to do this because I am making many tables from a large dataframe, each of which will have a different title

Here is example data

d <- data.frame(
          organism=c("Grasshopper", "Bumblebee", "MycoTB"), 
          protein=c("Jumpylegs", "venom-1", "rpoB"), 
          accession=c("Gr1,Gr2,Gr3", "Bbv4,Bbv5,Bbv6", "Mtb1,Mtb2,Mtb3,Mtb4,Mtb5"), 
          title = c("mytitle", "mytitle", "mytitle")
)

Here is my code

d %>%
          gt() %>%
          tab_header(
                    title = # here I want to get the text from the title column, somthing like .$title[1]
                
          )

Solution

  • d %>%
      gt() %>%
      tab_header(
        title = .$`_data`$title[1]
      )
    

    When you convert your data to a gt object, you can access the data elements in the list using _data.

    This gives us: