简体   繁体   English

使用Purrr :: map生成多个htmlTable的函数

[英]Function to Generate Multiple htmlTables using Purrr::map

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. 我想创建一个为数据集中所有分类变量创建频率表的函数,然后为每个变量生成htmlTables。 However, by using purrr::map, the tables are in a list. 但是,通过使用purrr :: map,这些表位于列表中。 How do I generate the tables using htmlTable? 如何使用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? 我想我需要分割列表或使用其他purrr :: map函数吗? Help would be appreciated... 帮助将不胜感激...

Something like this...


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

Here's a solution that uses a tibble to store the arguments to the function as well as the resulting HTML strings: 这是一个使用tibble存储该函数的参数以及结果HTML字符串的解决方案:

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表格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM