Search code examples
rexportjpeg

R exporting plots through a for cycle


I have a problem exporting some statistical plot on R. I am using the function jpeg() with the function dev.off()...I have replicated the code and it gives me the same error:

data1<-rnorm(n = 1000,mean = 0,sd = 1)
data<-cbind(data,data,data,data)

for(i in c(1,2,3)){
  print(i)
  if(i ==1){
    #Histograms and density
    jpeg(paste(getwd(),'/Hist_',i,'.jpg',sep=''))
    histogram( data[,1],xlab = "data" )
    dev.off()
    #boxplot
    jpeg(paste(getwd(),'/Boxplot_',i,'.jpg',sep=''))
    boxplot(data[,1],xlab='cluster', ylab='data')
    dev.off()
  }else{
    #Histograms and density
    jpeg(paste(getwd(),'/Hist_',i,'.jpg',sep=''))
    histogram( data[,1],xlab = "data" )
    dev.off()
    #boxplot
    jpeg(paste(getwd(),'/Boxplot_',i,'.jpg',sep=''))
    boxplot(data[,1],xlab='cluster', ylab='data')
    dev.off()
  }
}

if I set i=1 and then I run the relative cycle I have no problems, but if I run the entire cycle R exports only the boxplot images....does anyone know why? thank you !


Solution

  • The only problem in your code is data<-cbind(data,data,data,data) where it show be data<-cbind(data1,data1,data1,data1) and the fact that histogram is not base-r function. If you fix above, and set histogram=hist, everything works fine.