0

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

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

1 Answers1

1
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

Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • Yes, c is your table object. When converted to a tibble it comes in in a longer format, where the b value is defined in a column called `b` and the count is in another column called `n`. The pivot_wider step converts that to a wide table like your original `table` object. – Jon Spring Apr 22 '21 at 16:54
  • I tried to run it but I get this error: `Error in as.data.frame.default(value, stringsAsFactors = FALSE) : cannot coerce class ‘"function"’ to a data.frame`. – Jesús Asdrúbal Molina Víquez Apr 22 '21 at 16:55
  • Please ignore my last comment. I forgot to include a code line from your answer. Thanks for your help – Jesús Asdrúbal Molina Víquez Apr 22 '21 at 17:07