0

I have a code to process data, and I need to save some histograms that I will use in a Shiny application.

What I need is basically automate the creation of histograms, saving the result in a list of hist() objects, that I will save in an RDS file and then simply call in my Shiny app.

The code below shows the output that I want, but the variables names are hard coded, and it's not viable for me.

# 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

Thanks in advance.

Wlademir.

1 Answers1

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)

You may wan't to modify object naming to your liking, and not necessarily nest the plots.

runr
  • 1,142
  • 1
  • 9
  • 25