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

时间:2018-11-22 16:04:35

标签: r shiny dplyr histogram tibble

我有一个处理数据的代码,我需要保存一些将在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

先谢谢了。

Wlademir。

1 个答案:

答案 0 :(得分:1)

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)

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