Search code examples
rsavepng

R png() Function Adding Extra Stuff to Filenames and Ignoring Image Size Flags


I have an R script working and it is nearly done but there is one final problem. I am using the png(filename = " ", width = N, height = M, units =" ", ...) function in R but it is appending the width, height, and units flags to the png filenames. I can't find a way in the default help to fix this.

The exact command I am using is

 for(i in 1:length(lst)){
 
 png(paste0(filename = paste( lst[i]), ".png", width = 1280, height = 688, units = "px"))
 
 ...all plotting code...

 dev.off()

 }

Where lst[i] a list of filenames read through a loop. I end up with the .png files being called

idq27qecq.png1280688px where 1280688px is the stuff I dont want in the name. The png files are also all incorrectly sized, and have a size of 480 by 480 pixels.

How can I fix this?

If I remove the paste0 at the beginning I get the error

Error in png(filename = paste(lst[i]), ".png", width = 1280, height = 688, : invalid 'pointsize' argument

and also

In png(filename = paste(lst[i]), ".png", width = 1280, height = 688, : NAs introduced by coercion

Any help fixing the names and sizes of my output images would be helpful. I looked at this post save multiple plots r into separate jpg but it did not work even though I tried to implement it.

All of this is being done in the Rstudio engine through a script.


Solution

  • The first paste0 is not needed, also the second paste should be used only to create filename value. Try :

    for(i in 1:length(lst)){
      png(filename = paste(lst[i], ".png"), width = 1280, height = 688, units = "px")
      #  
      #...all plotting code...
      #
      dev.off()
    }