我正在创建一个函数,用于在州-城市级别的数据框中为各个州创建 gt 表。我将经常更改数据以及 gt 中选定的列,因此我向函数调用添加了许多输入参数,以便我可以更改它并相应地使用它。我想使用 purrr::map 函数作为伪 for 循环来迭代数据上的函数,同时可以自由地更改输入的数据源和 gts 中选定的列。
问题是,当我尝试使用映射函数让它迭代数据时,我不知道如何更改映射函数以适应多个输入。
如何更改地图功能来实现此目的?在这种情况下,如何使用我编写的函数为示例数据中的每个状态创建单独的 gt?如果有不同/更简单的方法来完成此任务,我们将不胜感激。这是我尝试过的:
library(gt)
library(tidyverse)
## WRITE THE FUNCTION
make_gts <- function(df, x, def_var, select_vect, title_text){
df_ind <- df %>% filter(def_var == x)
df_ind_clean <- df_ind %>%
select(all_of(select_vect))
gt(df_ind_clean) %>%
tab_header(title = paste("This is a GT for", title_text))
return(gt)
}
## DEFINE ARGUMENTS OF THE FUNCTION
title_text = "Elevation and NumObserved"
select_vect <- c("City", "Elevation", "NumObserved")
def_var <- df$State
## CREATE MAP LIST
iterate_list <- unique(def_var)
## GT LIST
state_gt_list <- set_names(iterate_list) %>%
purrr:map(make_gts(df = ex_data,
def_var = df$State,
x = iterate_list[i],
select_vect = select_vect,
title_text = title_text))
样本数据:
df <- structure(list(State = c("California", "California", "California",
"Texas", "Texas", "Texas", "New Mexico", "New Mexico", "New Mexico"
), City = c("Los Angeles", "San Francisco", "Fresno", "Dallas",
"Austin", "Frisco", "Albuquerque", "Santa Fe", "Taos"), NumObserved = c(1200000L,
825000L, 113000L, 240000L, 189000L, 38000L, 56000L, 23000L, 6000L
), Elevation = c(28L, 47L, 235L, 312L, 550L, 128L, 4291L, 3533L,
7823L)), class = "data.frame", row.names = c(NA, -9L))
扩展我的评论,并返回标准小标题,因为我没有
gt
包...
df %>%
group_by(State) %>%
group_map(
function(.x, .y, select_vect) {
df_ind_clean <- .x %>%
select(all_of(select_vect))
# gt(df_ind_clean) %>%
# tab_header(title = paste("This is a GT for", title_text))
# return(gt)
df_ind_clean
},
select_vect=c("City", "Elevation", "NumObserved")
)
给予
[[1]]
# A tibble: 3 × 3
City Elevation NumObserved
<chr> <int> <int>
1 Los Angeles 28 1200000
2 San Francisco 47 825000
3 Fresno 235 113000
[[2]]
# A tibble: 3 × 3
City Elevation NumObserved
<chr> <int> <int>
1 Albuquerque 4291 56000
2 Santa Fe 3533 23000
3 Taos 7823 6000
[[3]]
# A tibble: 3 × 3
City Elevation NumObserved
<chr> <int> <int>
1 Dallas 312 240000
2 Austin 550 189000
3 Frisco 128 38000
这接近你想要的吗?