Search code examples
rgt

tab_spanner returning column does not exist


I am trying to create a table using the gt package. Now when I try to add a spanner to the table, the code returns an error.

gt_tbl =
  gt(data = merged.dfs) %>%
  tab_header(
    title = "Two sample K-S Test Statistics for 2004") %>%
  tab_spanner(
    label = "Pair 1 (VIC SC and PCA SC)",
    columns = c(D.Max.04.p1, p.value.04.p1)
  ) %>%
  tab_spanner(
    label = "Pair 2 (VIC SCB1 and PCA SCB1)",
    columns = c(D.Max.04.p2, p.value.04.p2)
  ) 

Error

Error: Can't subset columns that don't exist.
x Column `0.19` doesn't exist.

Please note that when I run the the following code, the table gets created, and it can be seen the columns do actually exist. How can this error be fixed?

gt_tbl =
      gt(data = merged.dfs) %>%
      tab_header(
        title = "Two sample K-S Test Statistics for 2004")  

enter image description here


Solution

  • The columns argument is being evaluated, and so the code is looking for columns which have names equal to the values of merged.dfs$D.Max.04.p1 and merged.dfs$p.value.04.p1, hence the first column it is looking for is merged.dfs$0.19. There are two ways you can modify the columns argument:

    Use quoted strings:

    columns = c("D.Max.04.p1", "p.value.04.p1")
    

    use the vars function (as shown in the example for ?tab_spanner)

     columns = vars(D.Max.04.p1, p.value.04.p1)
    

    Of course the same change will need also to be applied to the second tab_spanner call too.