在使用 purrr 进行迭代时,如何强制 R 中的自定义函数以设定的顺序产生多个 outputs/plots?

How to coerce custom function in R to yield multiple outputs/plots in a set order when iterating with purrr?

我有一个自定义函数,可以为每个数据切割绘制 3 个图。第一个图是总体结果,后面应该是按位置和级别细分的结果(尽管位置或级别是第二或第三都可以,只要它是一致的)。

虽然我的功能有效,但它首先放置了位置图,然后是整体图,然后是级别图。我很困惑为什么会发生这种情况,因为 2 个子图是在 plot2 中制作的,在我的输出中,我明确指定整体图应该放在第一位。

这个 post 对于让我的自定义函数产生 2 个输出非常有帮助,但是这个 post 没有涵盖如何将你的输出限制在特定的顺序。

这是我的代码:


#Data
test <- tibble(s1 = c("Agree", "Neutral", "Strongly disagree"),
               s2rl = c("Agree", "Neutral", "Strongly disagree"),
               f1 = c("Strongly agree", "Disagree", "Strongly disagree"),
               f2rl = c("Strongly agree", "Disagree", "Strongly disagree"),
               level = c("Manager", "Employee", "Employee"),
               location = c("USA", "USA", "AUS"))

#Get just test items for name
test_items <- test %>%
  dplyr::select(s1, s2rl, f1, f2rl)

#titles of plots for R to iterate over
titles <- c("S1 results", "Results for S2RL", "Fiscal Results for F1", "Financial Status of F2RL")


#group levels
group_name <- c("level", "location")

#custom ggplot function
faceted_plots = function(variable, group, title) {
  
  plot1 <- test %>%
    count(.data[[variable]]) %>%
    mutate(percent = 100*(n / sum(n, na.rm = TRUE))) %>%
    ggplot(aes(x = .data[[variable]], y = percent, fill = .data[[variable]])) + 
    geom_bar(stat = "identity") +
    ggtitle(title)

  plot2 <- test %>%
    count(.data[[group]], .data[[variable]]) %>%
    mutate(percent = 100*(n / sum(n, na.rm = TRUE))) %>%
    drop_na() %>%
    ggplot(aes(x = .data[[variable]], y = percent, fill = .data[[variable]])) + 
    geom_bar(stat = "identity") +
    geom_text(aes(label= paste0(percent, "%"), fontface = "bold", family = "Arial", size=14), vjust= 0, hjust = -.5) +
    labs(
      title = title) +
    facet_grid(~.data[[group]])
  
  output <- list(plot1, plot2)
  return(output)
}

#pmap call
my_plots <- expand_grid(tibble(item = names(test_items), title=titles),
                        group = group_name) %>%
  pmap(function(item, group, title)
    faceted_plots(item, group, title))

my_plots

虽然我没有弄清楚如何按特定顺序强制元素,但我找到了删除重复项的方法(这是我上面示例中的问题——总体图或 plot1 是被生产两次)基于此 .

适用于此示例,即:

# make a copy of my original list of plots to avoid duplicates
my_plots_duplicate <- my_plots
# take set difference between contents of list elements and accumulated elements
my_plots_duplicate[-1] <- mapply(setdiff, my_plots_duplicate[-1],
                       head(Reduce(c, my_plots, accumulate=TRUE), -1))

my_plots_duplicate