Search code examples
rexpss

how to further refine expss table format?


I am trying to improve my table design using expss. My current design is shown below using the following code:

library(expss)
# bogus example data
x<-structure(list(visits= structure(c(17, 2, 23, 1, 21), label = "Total # Home Visits", class = c("labelled", "numeric")), months_enrolled = structure(c(21.42474, 51.105, 52.474, 53.75, 60.0392105), label = "Enrollment Duration (months)", class =c("labelled","numeric")), marital2 = structure(c("Married", NA, "Married", "Married", "Married"), label = "Marital Status", class = c("labelled", "character")), Relationship2 = structure(c("Mother", "Mother", "Mother", "Mother", "Mother"), label = "Relationship (recoded)", class = c("labelled", "character"))), row.names = c(NA, 5L), class = "data.frame")

htmlTable(x %>% 
tab_cells(visits,months_enrolled) %>%
tab_rows(marital2, Relationship2,  total()) %>%     tab_stat_fun(Mean = w_mean, "Valid N" = w_n, method = list) %>%
tab_pivot() %>%
set_caption("Table 6: Bogus Visits and Duration by Characteristics") %>% 
htmlTable(.,css.cell = c("width: 220px", # first column width
                          rep("width: 50px", ncol(.) - 1))))

I'd like to improve the table design by placing the mean statistics for Home Visits and Enrollment Duration as columns, thus saving a row for each level of Marital Status (and other vars in tab_rows). How is this achieved? Also, is it possible to shade alternate rows?

expssTable


Solution

  • It seems, the simplest way is to transpose table:

    htmlTable(x %>% 
                  tab_cells(visits, months_enrolled) %>%
                  tab_cols(marital2, Relationship2,  total()) %>%  
                  tab_rows(total(label = "|")) %>% 
                  tab_stat_fun(Mean = w_mean, "Valid N" = w_n) %>%
                  tab_pivot() %>%
                  tab_transpose() %>% 
                  set_caption("Table 6: Bogus Visits and Duration by Characteristics") %>% 
                  htmlTable(.,css.cell = c("width: 220px", # first column width
                                           rep("width: 50px", ncol(.) - 1))))
    

    enter image description here