[英]How to mutate multiple columns with dynamic variable using purrr:map function?
[英]Function to Generate Multiple htmlTables using Purrr::map
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)
}
这是一个使用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
这是它创建的表之一的屏幕截图:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.