Search code examples
rresampling

R- resampling one coarser resolution raster image with finer one


I have 2 raster images of different spatial resolution and projection. I want to resample multiple coarser images (0.25 degrees) to finer resolution(4 km) based on one finer resolution image which is of 4 km.

Both are in different folders. I had tried to write the code in R but I'd got error.

 >library(raster)
 >setwd("D:/mtech project/data/DEC 16/RH/1-DEC-16/extracted/")
 >inFiles1 <- list.files(pattern="*.tif")
 > nFiles1 <-  length(inFiles1)
 > setwd("D:/mtech project/data/extracted/")
 > inFiles2 <- raster("3DIMG_01DEC2016_0000_L2C_FOG_FOG.tif")
 > for (i in 1:nFiles1) {
 +     r1<-raster(inFiles1[[i]])    
 +     r2<-inFiles2    
 +     rs<-resample(r1,r2,method="bilinear")
 +     write.Raster(rs, paste0('D:/mtech project/data/DEC 16/RH/RESAMPLED/rs_',i,'.img'), overwrite=T)
 +   }

 Error in .local(.Object, ...) : 

 Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer",  :   Cannot create a RasterLayer object from this file. (file does not exist)

`


Solution

  • If a function with a loop does not work, try to run it for the first case, without the loop. The error messages you get is pretty clear. The file does not exists, as you only have the file name, but not the path name, and you changed directories.

    Instead you could do this:

    library(raster)
    ff <- list.files("D:/mtech project/data/DEC 16/RH/1-DEC-16/extracted/", pattern="\\.tif$", full.names=TRUE)
    n <- length(ff)
    r2 <- raster("D:/mtech project/data/extracted/3DIMG_01DEC2016_0000_L2C_FOG_FOG.tif")
    for (i in 1:n) {
        r1 <- raster(ff[i])    
        f <- paste0('D:/mtech project/data/DEC 16/RH/RESAMPLED/rs_',i,'.img')
        rs <- resample(r1, r2, method="bilinear", filename=f, overwrite=TRUE)
    }
    

    Or avoid the loop altogether and write to a single file.

    s <- stack(inFiles)
    f <- 'D:/mtech project/data/DEC 16/RH/RESAMPLED/rs.img'
    rs <- resample(s, r2, method="bilinear", filename=f, overwrite=TRUE)