1
votes
library(htmlTable)
library(tidyverse)
library(ggmosaic) for "happy" dataset

I want to create a function that creates frequency tables for all the categorical variables in a dataset and then generate htmlTables for each one. However, by using purrr::map, the tables are in a list. How do I generate the tables using htmlTable? Or any better package that generates similar tables for publication? I suppose I need to split the list or use additional purrr::map functions? Help would be appreciated...

Something like this...


FUN<-function(data){
TAB<-happy%>%select_if(is.factor)%>%
map(table)
TABLES<-htmlTable(TAB)
return(TABLES)
}
1

1 Answers

0
votes

Here's a solution that uses a tibble to store the arguments to the function as well as the resulting HTML strings:

Edit: added new column (percent)

library(ggmosaic) 
library(purrr)
library(tidyverse) 
library(htmlTable)
library(magrittr) 
library(scales)

data(happy)

# Use a subset of `happy` for the example
h <- happy %>% as_tibble %>% sample_n(100)

# create the function
make_html_table <- function(data, .name, .col_names) {
  data %>% 
    table %>% 
    as.data.frame %>% 
    set_colnames(.col_names) %>% 
    as.data.frame %>% 
    mutate(percent = scales::percent(count/sum(count))) %>%  # add the percent column
    htmlTable(caption = .name)
}

# Apply the function and store the results in a tibble
tbl <- 
    h %>% 
    select_if(is.factor) %>% 
    { tibble(NAME = names(.), 
             data = map(., ~.x)) } %>% 
    mutate(TABLE = map2(.x = data, 
                        .y = NAME, 
                        .f = make_html_table, 
                        .col_names = c("levels", "count")))

# Check out the tables in the Viewer Pane (if you're using RStudio)
tbl %>% extract2("TABLE") %>% map(htmlTableWidget)
#> $happy
#> 
#> $sex
#> 
#> $marital
#> 
#> $degree
#> 
#> $finrela
#> 
#> $health

Here's a screenshot of the one of the tables this creates:

html table