Search code examples
rmergerbindgt

Is there an R function for binding two tables next to each other but having a title over the whole thing?


I have been using the gt package in R to create tables for a paper. I have been using rbind to stack the two tables on top of each other but would rather they are next to each other with one title going across. The two tables are displaying the same statistics output for many variables and this would be easier to understand than one long table. For example I have: Table A:

estimate p-value
X. 1        0.5
Y. 2        0.03
Z. 9        0.001

Table B:

estimate p-value
X. 3        0.05
Y. 4        0.01
Z. 10       0.001

and I want:

Table: Type 3 fixed effects
A:                  B:
estimate p-value  estimate p-value
X. 1        0.5      3        0.5
Y. 2        0.03     4        0.03
Z. 9        0.001    10       0.001

my code is currently:

rbind(tableA,tableB)%>%
  gt()%>%
  fmt_number(
    columns = everything(),
    decimals = 3
  )%>%
  cols_label(
    effect = md("**Effect**"),
    f_value = md("**F Value**"),
    formatted_p_value=md("**P Value**")
  )%>%
  tab_row_group(group = md('**Table A**'), rows = 1:nrow(tableA)) %>%
  tab_row_group(group = md('**Table B**'), rows = (nrow(tableA) + 1):(nrow(tableA) + nrow(tableB))) %>%
  tab_header(
    title = md("**Table 2: Type 3 Fixed Effects**")
  )

I am using the table_row_group function to separaate the two data sets that I want to be next to each other instead. I also tried cbind and cols_bind but was having trouble getting them to work with the gt package. I am open to using kable() but the output looks very different from the gt output and i am not as familiiar with this package. Any help is aappreciated, Thank you!


Solution

  • library(tidyverse)
    library(gt)
    
    tableA <- 
      tibble::tribble(
        ~estimate, ~"p-value",
        "1","0.5",
        "2","0.03",
        "9","0.001"
      )
    
    tableB <- 
      tibble::tribble(
        ~estimate, ~"p-value",
        "3","0.05",
        "4","0.01",
        "10","0.001"
      )
    

    Does this work?

    bind_cols(tableA, tableB) |> 
      gt()|>
      fmt_number(
        columns = everything(),
        decimals = 3
      ) |>
      tab_spanner("A", 1:2) |>
      tab_spanner("B", 3:4) |> 
      tab_header(
        title = md("**Table 2: Type 3 Fixed Effects**")
      ) |> 
      cols_label(
        "estimate...1" = "Effect",
        "p-value...2" = "P Value",
        "estimate...3" = "Effect",
        "p-value...4" = "P Value"
      )
    

    enter image description here