Search code examples
rdataframegt

How maked beautiful tables from table object in R


I want to make a beautiful table from table in R. This is the table created from factor variables:

a=factor(sample(1:4, 10000, replace=TRUE))

b=factor(sample(c(0,1,NA), 10000, replace=TRUE))

table(a,b,exclude=NULL)

This is the output from table command:

  b
a     0   1 <NA>
  1 855 824  851
  2 802 843  870
  3 821 868  855
  4 795 786  830

I want to know how can I add tittle to this table and format to make a beautiful table like using gt or another similar package


Solution

  • c <- table(a,b,exclude=NULL)
    
    library(dplyr); library(tidyr); library(gt)
    
    c %>%
      tibble::as_tibble() %>%
      tidyr::pivot_wider(names_from = b, values_from = n) %>%
      gt::gt() %>%
      gt::tab_header(
        title = "How do A and B coincide?",
        subtitle = "Such a great table"
      ) %>% gt::tab_spanner(
        label = "b",
        columns = 2:4
      )
    

    enter image description here