Search code examples
reconomics

How to make this matrix like table in the R for the total count?


I want to reproduce the attached table but am not able to do it whatsoever. which package should i use? can anyone redirect me to the right path?

the data look like the following,

ID   a     b     c    d
 x   1     0     0    1
 y   0     0     1    1
 z   0     1     1    0
 w   1     1     0    0


enter image description here


Solution

  • If your question is to convert the data you have into a table form that's more aesthetically pleasing, the flextable package may be an easy one to use. You can also get the counts of your data by using adorn_totals by column and by row. I have tried to recreate your data below and build a table around it:

    #### Load Libraries ####
    library(tidyverse) # for piping 
    library(flextable) # for table
    library(janitor) # for row and column totals
    
    #### Use Same Data ####
    ID <- c("x","y","z","w")
    a <- c(1,0,0,1)
    b <- c(0,0,1,1)
    c <- c(0,1,1,0)
    d <- c(1,1,0,0)
    
    #### Just Use Adorn Totals ####
    df <- data.frame(ID,a,b,c,d) %>% 
      adorn_totals("col") %>% 
      adorn_totals("row")
    
    #### Flextable ####
    df %>% 
      flextable() %>% 
      add_header_lines("Total by Total Version")
    

    Which gives you this:

    enter image description here