【问题标题】:Function to Generate Multiple htmlTables using Purrr::map使用 Purrr::map 生成多个 htmlTables 的函数
【发布时间】:2017-03-25 06:10:38
【问题描述】:
library(htmlTable)
library(tidyverse)
library(ggmosaic) for "happy" dataset

我想创建一个函数,为数据集中的所有分类变量创建频率表,然后为每个变量生成 htmlTables。但是,通过使用 purrr::map,这些表在一​​个列表中。如何使用 htmlTable 生成表格?或者有什么更好的包可以生成类似的发布表?我想我需要拆分列表或使用额外的 purrr::map 函数?帮助将不胜感激...

Something like this...


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

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    这是一个解决方案,它使用 tibble 来存储函数的参数以及生成的 HTML 字符串:

    编辑:添加了新列(百分比)

    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
    

    这是创建的其中一个表的屏幕截图:

    【讨论】:

    • 谢谢,这就是我想要的,但只是一些事情。一、我好像没有htmlTableWidget?我尝试做 tbl%>%extract2%>%("TABLE")%>%map(htmlTable) ,它只显示了健康的 html 表,这是列表的最后一个。另外,我可以使用 tidyr::unnest 代替 extract2 吗?
    • 对于“将结果存储在 Tibble”部分,这段代码中 { } 的用途是什么?我没有尝试过,它说“每个变量必须是一维原子向量或列表”。我不确定这意味着什么?
    • 最后,有没有办法在 make_html_table 函数中添加百分比?有一个计数和百分比列会很棒。百分比是我最追求的!我也发布了另一个问题,哈哈
    • htmlTableWidget 是 htmlTable 包 (v1.9) 中的一个函数 unnest 用于扩展嵌套数据框,在这种情况下不是必需的
    • { } 防止 %>% 的左侧作为第一个参数自动传递到 %>% 的右侧
    猜你喜欢
    • 2017-07-19
    • 1970-01-01
    • 2019-12-20
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多