Home > Mobile >  How to save plots in a loop to different pdfs in R?
How to save plots in a loop to different pdfs in R?

Time:05-04

in each itteration of a loop I want to save my plots into a pdf. I have found some good code examples (e.g. here), but for some reason it doesn´t work in my case. What have I been doing wrong?

I did the following:

save_as = "xxxx.pdf"

# dataframe 
Var1 <- c(1.0, 1.4, 2.0, 0.7, 0.8, 1.3, 1.6, 0.9, 0.5)
Var2 <- c(100, 99, 320, 219, 280, 299, 210, 200, 190)
Var3 <- c(10, 1, 4, 8, 19, 20, 7, 8, 2)
indep1 <- c(10, 11, 14, 25, 23, 21, 33, 11, 14)
indep2 <- c("species1", "species1", "species2", "species3", "species1", "species3", "species2", "species2", "species2")

df <- data.frame(Var1, Var2, Var3, indep1, indep2)

# dependent variables
dep_vars = c("Var1", "Var2", "Var3")

for (i in dep_vars){  
  ## model specification
  model1 = lmer(eval(parse(text=paste("df$", i, sep = ""))) ~ df$indep1   (1|df$indep2))
  model2 = lmer(eval(parse(text=paste("df$", i, sep = ""))) ~ (1|df$indep2))

  # open pdf
  new_save_as = gsub('xxxx', i, save_as)
  pdf(new_save_as)

  # put plots in 
  par(mfrow = c(1,2))

  plot(model1, type=c("p", "smooth"), col.line=1)
  plot(model2, type=c("p", "smooth"), col.line=1)
  
  # close file
  dev.off()
}

If I run this without the loop, the file is created as I want it. But, if I use the loop the pdf is created but stays empty. Does anyone have an idea why?

Also, any other comments on my code are welcome, as I am new to R.

Thanks!

CodePudding user response:

If we want to use a loop, the eval(parse would not be the best way. Instead use [[ to subset the column

for (i in dep_vars){  
  
  model1 = lmer(df[[i]] ~ df$indep1   (1|df$indep2))
  model2 = lmer(df[[i]]~ df$indep1   (1|df$indep2))

  # open pdf
  new_save_as = gsub('xxxx', i, save_as)
  pdf(new_save_as)

  # put plots in 
  par(mfrow = c(1,2))

  print(plot(model1, type=c("p", "smooth"), col.line=1))
  print(plot(model2, type=c("p", "smooth"), col.line=1))
  
  # close file
  dev.off()
}
  • Related