【问题标题】:How to loop over a functionalized plot in R?如何遍历R中的功能化图?
【发布时间】:2021-07-23 13:50:40
【问题描述】:

这是我的数据集:

df_table <- data.frame(user = c("User1", "User2", "User3"), opened_dates = c("2021-07-01", "2021-08-02", "2021-09-03"), num_active_users = c(5, 18, 11))

我有以下函数用于为我的数据集中的所有用户创建一个绘图。

daily_active_users <- function(data, user, plot_color = "blue") {
ggplot(data, aes(x = opened_dates, y = num_active_users, fill = plot_color)) + 
geom_col() + 
theme(legend.position = "none") +
labs(title = paste0(user, ": Daily # Active Users"), y = "# Active Users")}

目前我必须手动指定用户来为每个人运行绘图

daily_active_users(df_table, "User1", plot_color = "blue")

我想要一种方法来遍历所有用户,而不必像上面那样手动执行此操作。这样做的最佳方法是什么?

【问题讨论】:

  • lapply(df_table%&gt;% distinct(user)%&gt;%pull(user), function(x) daily_active_users(df_table, x)) 将在list 中为您提供绘图。
  • @Limey 谢谢!

标签: r function loops


【解决方案1】:

使用 tidyverse 的 purrr::map() 并对函数顺序稍作修改,您可以尝试:

library(tidyverse)
library(patchwork)

df_table <- data.frame(user = c("User1", "User2", "User3"), opened_dates = c("2021-07-01", "2021-08-02", "2021-09-03"), num_active_users = c(5, 18, 11))

# Note that I switched the order of the parameters "user" and "data"
daily_active_users <- function(user, data, plot_color = "blue") {
  ggplot(data, aes(x = opened_dates, y = num_active_users)) + 
    geom_col(fill = plot_color) + # Note that I moved plot_color here, to actually get the plot in the color you request.
    theme(legend.position = "none") +
    labs(title = paste0(user, ": Daily # Active Users"), y = "# Active Users")}

list_of_figures <- 
  map(.x = df_table$user, 
      .f = daily_active_users, 
      data = df_table)

# Plot the list of figures
list_of_figures[[1]]/list_of_figures[[2]]/list_of_figures[[3]]

【讨论】:

    【解决方案2】:

    根据上面@Limey 的评论,您可以使用lapply()。将user 参数移动到第一个参数以避免必须使用function(x) 可能会有所帮助。所以:

    df_table <- data.frame(user = c("User1", "User2", "User3"), opened_dates = c("2021-07-01", "2021-08-02", "2021-09-03"), num_active_users = c(5, 18, 11))
    
    daily_active_users <- function(user, data, plot_color = "blue") {
        ggplot(data,
               aes(x = opened_dates, y = num_active_users, fill = plot_color)
        ) + 
        geom_col() + 
        theme(legend.position = "none") +
        labs(
            title = paste0(user, ": Daily # Active Users"),
            y = "# Active Users")
    }
    users <- df_table %>% distinct(user) %>% pull(user)
    plts <- lapply(users, daily_active_users, df_table) %>%
        setNames(users)
    

    然后您可以使用plts[[&lt;user&gt;]] 引用每个图,例如:

    plts[["User2"]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-20
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 2023-03-18
      • 2021-11-17
      • 2014-12-05
      相关资源
      最近更新 更多