Loop over a function that automatically generates a plot and store the plots in a single pdf file with a plot title in each page (R)

14 views Asked by At

I'm working with a function - did_multiplegt - which automatically creates a plot. I want to loop over a set of outcomes Y, in which I:

  1. run the function with that outcome Y_1
  2. save the regression results in a dataframe
  3. save the plot automatically generated adding a title with the variable name as a page in a pdf file that I open at the beginning of the loop

So far, I think I managed to do everything, but I can't add the title to the plot. The issue is that I can't store the plot created as a ggplot, and so, I can't add the title. This is a problem because I end up with a pdf with a bunch of plots and it's hard to tell what is what.

Also, given that running this command takes a long time, I would like to avoid running it twice (once to store the plot and once to store the coefficients).

Here's a reproducible example of my code. Thanks!

# Packages
library("wooldridge")
library("DIDmultiplegt")
library(ggplot2)

# Create a tidier for "multiplegt" objects (can be skipped)
tidy.did_multiplegt = function(x, level = 0.95) {
  ests = x[grepl("^placebo_|^effect|^dynamic_", names(x))]
  ret = data.frame(
    term      = names(ests),
    estimate  = as.numeric(ests),
    std.error = as.numeric(x[grepl("^se_placebo|^se_effect|^se_dynamic", names(x))]),
    N         = as.numeric(x[grepl("^N_placebo|^N_effect|^N_dynamic", names(x))])
  ) |>
    # For CIs we'll assume standard normal distribution
    within({
      conf.low  = estimate - std.error*(qnorm(1-(1-level)/2))
      conf.high = estimate + std.error*(qnorm(1-(1-level)/2))
    })
  return(ret)
}

# Define variables
G <- "nr"
T <- "year"
D <- "union"

# List of outcome variables
outcome_list <- c("lwage", "hours")

# pdf directory and name
name <- "C:/Users/madda/trash/try_plot.pdf"

# Open pdf
pdf(name)


# Loop over outcome variables
for (i in 1:length(outcome_list)) {
  
  Y <- outcome_list[i]  # Estimate the effect using did_multiplegt function
  
  result <- did_multiplegt(wagepan, Y, G, T, D, placebo = 2, dynamic = 5, 
                           brep = 2, cluster = G)
  

  
  if (i == 1){
    results_clean <-  tidy.did_multiplegt(result)
    
  } 
  
  else{
    
    result <- tidy.did_multiplegt(result)
    results_clean <- rbind(results_clean, result)
    
  }
  
 # My problem is here 
  ggplot(results_clean)
  plot_res <- ggplot(results_clean) + ggtitle(paste0("Plot", Y))
  plot(plot_res)
 # My problem finishes here

}

dev.off()

I've tried to save the plot as a gg object, to do somthing like

  title <- paste0("Plot", Y)
  res_plot <- recordPlot()
  res_plot_fin <- res_plot + title

And several other combinations of this.

Any help is highly appreciated, thank you!

0

There are 0 answers