How to make a cycle that takes multiple rasters and mosaics them in R? And save them with an specific name

440 Views Asked by At

I have around of 2000 raster files of different parts of the wolrd. Some of them are from the same day, and other are from different days. I want to mosaic/merge all the files that are from the same day to create "pictures" (rasters) by day.

All the names of the files begins with "MOD13A3.A2000" and then the day of the year the image was captured, and then other nonimportant stuff. The thing I want to do is to take all the files that start with the same name and merge them.

For example, I would take the first 4 files here, since they begin with MOD13A3.A2000032..., merge them and have just one file called MOD13A3.A2000032. And then take the other 4 following files, since they begin with MOD13A3.A2000061..., merge them and have another file called MOD13A3.A2000061.

MOD13A3.A2000032.h12v13.006.2015138123528 //

MOD13A3.A2000032.h13v13.006.2015138123527 //

MOD13A3.A2000032.h13v14.006.2015138123528 //

MOD13A3.A2000032.h14v14.006.2015138123526 //

MOD13A3.A2000061.h12v13.006.2015136111214 //

MOD13A3.A2000061.h13v13.006.2015136111225 //

MOD13A3.A2000061.h13v14.006.2015136111218 //

MOD13A3.A2000061.h14v14.006.2015136111220 //

...

I have been looking into other forums but since I am completely new to R programming I don't understand too much of the codes that are posted. I have thought about making a for cycle that changes the beginning of the file's name, like "MOD13A3.A2000"+i but I don't understand the sintaxis of it. I have not been able to find clear examples that show how to change a file's name like this either.

If someone could EXPLAIN a code, I would be SO GRATEFUL!

1

There are 1 best solutions below

0
Grzegorz Sapijaszko On

I would start with terra package:

library(terra)

r <- list.files(path = "rasters", pattern = "MOD13A3.A2000061.*", full.names = TRUE)
r <- lapply(r, rast)
r <- do.call(merge, r)

First line creates list of raster files with specific pattern, 2nd applies rast() function to them, and 3rd do merge.

Fill free to create a loop for patterns in your filenames: list.files reads the files, then take a substr() of filenames and find all unique() strings.