rfor-looppvclust

Function returning a plot not list of plots


I'm trying to run pvclust as a test Im running it in small subset of files. The issue is it works but instead of list which i would have used downstream to print it to individual files it gets printed.

My code

list_of_files <- list.files('Model_pvclust/',pattern = '\\.txt$', full.names = TRUE)


cmplx_ht<-function(file_list){
  start_time <- Sys.time()
  df_list<-list()
  #heat_list<-list()
  pv_list<-list()
  require(pvclust)
  
  for(f in file_list){
    message(paste0("Making pvclust for: ",f))
    
    #fname <- gsub("Model_hmap\/\/|\.txt","",f)
    df <- read.csv(f, header = TRUE, sep = "\t", check.names = FALSE)
    mat <- t(scale(t(as.matrix(df[,grepl("TCGA-",colnames(df))]))))
    rownames(mat)<-df$Symbol
    df_list[[f]]<-mat
    #print(head(mat))
   hm <-  pvclust(as.data.frame(t(mat)), method.hclust="complete",
            method.dist="euclidian",nboot = 10, parallel=T)
    
    #heat_list[[f]]<-hm 
    plot(hm)
   b <-pvrect(hm, alpha=.95)
   pv_list[[f]] <-b 
   #dev.off()
   
  # dev.off()
    message("Done")
  }
  end_time <- Sys.time()
  time_taken<- end_time-start_time
  message(paste0(time_taken,"s"))
  return(pv_list)
}

hm_lst<-cmplx_ht(list_of_files) 

To print it to individual files this is what Im doing

for (i in 1:length(hm_lst)) {
  file_name = paste(names(hm_lst)[[i]],".pdf", sep="")
  #file_name = paste(names(hm_lst),".pdf", sep="")
  
  pdf(file_name,width = 15,height = 10)
  draw(hm_lst[[i]])
  dev.off()
}

But my hm_list is coming empty the output is getting printed which i don't want. I want to store the output as lists the want to print it to files

Im not sure what exactly I'm doing wrong. Any suggestion or help would be really appreciated


Solution

  • You can use recordPlot to store a base plot in a object.

    x = 1:10
    
    plot(x)
    
    # record the plot
    g <- recordPlot()
    
    # clean the device
    plot.new()
    
    # plot is saved to g
    g
    
    

    plot in object g