I am doing Deseq2 analysis and would like to save all the plots in a single pdf file. For that i have written a function and try to use the function to save plots one after the other in a single pdf file. Here is the sample code and so far i was not succesful

pdf="Results_Deseq2.pdf"

if (!(is.null(pdf))){

pdf(pdf,paper="a4r")

}

window=function(x){

if(is.null(pdf)){

windows()

} else {

par(mfrow=c(1,1))

}

##### Analysis##########

window()

DESeq2::plotMA(dds)

dev.off()

rld <- rlog(dds, blind=FALSE) # rlog

vsd <- varianceStabilizingTransformation(dds, blind=FALSE)

notAllZero <- (rowSums(counts(dds))>0)

par(mfrow=c(2,2))

window()

meanSdPlot(log2(counts(dds,normalized=TRUE) + 1)) ## log transformation log2(n+1) counts

meanSdPlot(assay(rld[notAllZero,])) ##rlog transformation

meanSdPlot(assay(vsd[notAllZero,])) ##variance stabilizing transformation

distro_expr(rld,plot_type = "boxplot")

dev.off()