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

How to automate the creation of histograms in R, saving the result in a list of hist() objects?

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

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

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

# 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

提前致谢。

弗拉基米尔。

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)

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