Home > database >  For loop to execute a process and save the data set using specific name in R
For loop to execute a process and save the data set using specific name in R

Time:08-30

I have an original raster file (.tif format) and I want to blur it with a gaussian filter using different sigma parameters which are increasing with step 0.05 (i.e., sigma = 0.2, then sigma = 0.25, etc). Finally, I'd like like those newly created rasters to be saved with their original name the sigma value I used to create them (e.g., my original raster's name is evi.tif and my goal is the exported raster to be named as evi02.tif, evi025.tif etc). I have done this for a single raster but I have to repeat the process 15 more times for a range of sigma starting from 0.2 to 0.9 (step 0.05). Can anyone help me? Here is the code for a single raster.

evi = raster("path/evi.tif")

gf <- focalWeight(evi, 0.2, "Gauss")
r_gf <- focal(evi, w = gf)

writeRaster(r_gf, "path/evi02.tif")

Here is the input raster:

new("RasterLayer", file = new(".RasterFile", name = "C:\\Users\\nikos\\OneDrive\\Desktop\\tst\\evi.tif", 
    datanotation = "FLT8S", byteorder = "little", nodatavalue = -Inf, 
    NAchanged = FALSE, nbands = 1L, bandorder = "BIL", offset = 0L, 
    toptobottom = TRUE, blockrows = 256L, blockcols = 256L, driver = "gdal", 
    open = FALSE), data = new(".SingleLayerData", values = logical(0), 
    offset = 0, gain = 1, inmemory = FALSE, fromdisk = TRUE, 
    isfactor = FALSE, attributes = list(), haveminmax = FALSE, 
    min = Inf, max = -Inf, band = 1L, unit = "", names = "evi"), 
    legend = new(".RasterLegend", type = character(0), values = logical(0), 
        color = logical(0), names = logical(0), colortable = logical(0)), 
    title = character(0), extent = new("Extent", xmin = 983600, 
        xmax = 1033100, ymin = 976000, ymax = 1028800), rotated = FALSE, 
    rotation = new(".Rotation", geotrans = numeric(0), transfun = function () 
    NULL), ncols = 495L, nrows = 528L, crs = new("CRS", projargs = " proj=lcc  lat_0=28.62510126  lon_0=77  lat_1=28.375  lat_2=28.875  x_0=1000000  y_0=1000000  datum=WGS84  units=m  no_defs"), 
    history = list(), z = list())

Thank you

CodePudding user response:

evi = raster("path/evi.tif")
for (i in seq(from = 0.2, to = 0.9, by = 0.05)) {
  gf <- focalWeight(evi, i, "Gauss")
  r_gf <- focal(evi, w = gf)
  file_name <- paste0("evi", i, ".txt")

  ## Make sure here you supply full path to folder without the last "/"
  full_file_path = paste0("full_path_to_output_folder", "/", file_name)
  writeRaster(r_gf, full_file_path)
}
  • Related