1

I´m trying this code to look for NA and negative pixel values and replace it for 0. But it´s too slow. Any tip for improve the performance of it?

"all.files" is a list of address of the images. "r1" is the stack of Landsat images and "e" is the extents of some region of interest.

 for (i in 1:length(all.files)){ 
    r1<-raster(all.files[i])
    re1<-crop(r1,e)
    re1<-re1/10000
    re2<-as.matrix(t(re1))
    re1[which(is.na(re2))]<-0
  for (j in 1:length(re1)){
    if (re1[j]<0)
   (re1[j]<-0)}
writeRaster(re1,filename=paste(substr(all.files[i],80,86),"_crop2.tif",sep=""),format="GTiff",overwrite=TRUE)
}
  • fwiw, try using basename(all.files[i]) rather than substr. – mdsumner Oct 22 '15 at 21:49
  • Why are you coercing to a matrix? Just treat the raster object as a matrix and index appropriately. This will replace NA and negative values in a raster and keep it a raster object: x[is.na(x) | x < 0] <- 0 – Jeffrey Evans Oct 23 '15 at 0:27
3

You can use reclassify:

for (i in 1:length(files)){ 
    r <- raster(files[i])
    r <- crop(r, e)
    r <- r / 10000
    outf <- paste0(substr(files[i], 80, 86), "_crop2.tif")
    r <- reclassify(r, c(NA, NA, 0, -Inf, 0, 0), filename=outf, overwrite=TRUE)
}
1

To assign raster values to 0, you can do something like this:

r <- raster('yourraster.tif')
r[is.na(r)] <- 0   #Convert all NAs within extent of r to 0
r[r < 0] <- 0      #Convert all negative numbers to 0

You dont need to convert it to a matrix or anything like that. So:

for (i in 1:length(all.files)){ 
  r1<-raster(all.files[i])
  re1<-crop(r1,e)
  re1<-re1/10000
  re1[is.na(re1)] <- 0
  re1[re1 < 0] <- 0
  writeRaster(re1,filename=paste(substr(all.files[i],80,86),"_crop2.tif",sep=""),format="GTiff",overwrite=TRUE)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.