首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数使用Purrr::map生成多个htmlTables。

函数使用Purrr::map生成多个htmlTables。
EN

Stack Overflow用户
提问于 2017-03-25 06:10:38
回答 1查看 369关注 0票数 1
代码语言:javascript
复制
library(htmlTable)
library(tidyverse)
library(ggmosaic) for "happy" dataset

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

代码语言:javascript
复制
Something like this...


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

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-26 02:28:42

下面是一个使用tibble来存储函数的参数以及由此产生的HTML字符串的解决方案:

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

代码语言:javascript
复制
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

下面是创建的一个表的屏幕截图:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43013175

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档