代码之家  ›  专栏  ›  技术社区  ›  Wlademir Ribeiro Prates

如何在R中自动创建直方图,并将结果保存在hist()对象列表中?

  •  0
  • Wlademir Ribeiro Prates  · 技术社区  · 6 年前

    我有一个处理数据的代码,我需要保存一些直方图,以便在一个闪亮的应用程序中使用。

    我需要的基本上是自动创建柱状图,将结果保存在hist()对象列表中,保存在RDS文件中,然后只需调用我的应用程序。

    下面的代码显示了我想要的输出,但是变量名称是硬编码的,对我来说不可行。

    # Create data for this example 
    list_dfs <- list(
      dfA = data.frame(Var1 = rnorm(100), Date1 = rep(1:50, 2), Var2 = rnorm(100)*.55),
      dfB = data.frame(Var3 = rnorm(100), Date2 = rep(1:50, 2), Var4 = rnorm(100)*.55),
      dfC = data.frame(Var5 = rnorm(100), Date3 = rep(1:50, 2), Var6 = rnorm(100)*.55)
    )
    
    # Part that I want to automate
    list_plots <- list(
      dfA = NULL,
      dfB = NULL,
      dfC = NULL
    )
    
    list_plots$dfA <- lapply(list_dfs[[1]], function(x){hist(x, plot = FALSE)})
    list_plots$dfB <- lapply(list_dfs[[2]], function(x){hist(x, plot = FALSE)})
    list_plots$dfC <- lapply(list_dfs[[3]], function(x){hist(x, plot = FALSE)})
    
    # Desired output - Histograms saved in a list
    list_plots$dfA$Var1 %>% plot
    list_plots$dfA$Date1 %>% plot
    list_plots$dfA$Var2 %>% plot
    
    list_plots$dfB$Var3 %>% plot
    list_plots$dfB$Date2 %>% plot
    list_plots$dfB$Var4 %>% plot
    
    list_plots$dfC$Var5 %>% plot
    list_plots$dfC$Date3 %>% plot
    list_plots$dfC$Var6 %>% plot
    

    提前谢谢。

    1 回复  |  直到 6 年前
        1
  •  1
  •   runr    6 年前
    res <- lapply(list_dfs, function(z){
       ll <- lapply(z, function(x){
         hist(x, plot = FALSE)
       })
       names(ll) <- names(z)
       return(ll)
    })
    names(res) <- names(list_dfs)
    

    您可能不想根据自己的喜好修改对象命名,也不一定要嵌套绘图。