library(htmlTable)
library(tidyverse)
library(ggmosaic) for "happy" dataset
我想创建一个函数,为数据集中的所有分类变量创建频率表,然后为每个变量生成htmlTable。但是,通过使用purrr :: map,表位于列表中。如何使用htmlTable生成表格?或者任何更好的包生成类似的表以供发布?我想我需要拆分列表或使用额外的purrr :: map函数?帮助将不胜感激......
Something like this...
FUN<-function(data){
TAB<-happy%>%select_if(is.factor)%>%
map(table)
TABLES<-htmlTable(TAB)
return(TABLES)
}
答案 0 :(得分:0)
这是一个使用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
以下是其中一个表格的屏幕截图: