0

I have about 40 spatial rasters in the .tiff format in a folder. I'm trying to generate histograms from each of the rasters in R, and save each histogram as a jpeg in a separate folder. I wrote code to loop through each of the raster, create a histogram and save it using the 'jpeg' package.

setwd("G:/Research/MODIS Albedo Oct 08-July 09/Test") 
library(raster)
library(jpeg)
files <- list.files(path="G:/Research/MODIS Albedo Oct 08-July 09/Test", pattern=".tif",all.files=T, full.names=F, no.. = T) #generate a list of rasters in the folder
number<-length(files) #count the number of rasters
for(r in 1:number) #loop over each raster in the folder
{
  x<-raster(files[r], header=F) #load one raster file
  jpeg("G:/Research/MODIS Albedo Oct 08-July 09/test_histplots/r.jpg") #create jpeg using the name 'r' generated by loop 
  hist(x) #generate histogram
  dev.off()  
}

I want each of the generated jpeg to have a different name, ideally a subset of the original raster name. For example, if the original name of the raster is 'MODIS101_265', the jpeg's name should be 265. Here, 265 is the Julian date in the year. I'm assuming that this might involve using a format specifier like %d in C, but I'm not sure how this works in R.

When I run the above code, I get only one histogram. It seems the code is correctly looping over the original rasters, but saving all resultant histograms to a single jpeg.

Any advice will be helpful! Thanks!

small_world
  • 139
  • 5
  • 13
  • use `sprintf` or `paste` when generating the filename in the `jpeg` call. i.e. `jpeg(sprintf("G:/Research/MODIS Albedo Oct 08-July 09/test_histplots/r%04d.jpg", r))` – hrbrmstr Jul 08 '14 at 23:45

1 Answers1

1

Regular expression using gsub are your friend for getting the number out of the name. Assuming that all of your files are named the way your example is ("MODIS101_265.tif"), then the code below will work for you.

Also, welcome to R where for loops are slow and can usually be replaced by the faster lapply.

saveMyHist <- function(fileName) {
  fileNum <- as.numeric(gsub(".*_(\\d+)\\.tif", "\\1", fileName))
  x <- raster(fileName, header=F)
  jpeg(sprintf("G:/Research/MODIS Albedo Oct 08-July 09/test_histplots/%03d.jpg", 
    fileNum))
  hist(x)
  dev.off()
}

files <- list.files("/Users/home/Documents/Development/Rtesting", 
  pattern=".tif",all.files=T, full.names=F, no.. = T)
lapply(files, saveMyHist)
waternova
  • 1,472
  • 3
  • 16
  • 22