I have a long list of raster files that I want to upload in R to merge them. Here is a example of the files that I have in my directory
dir()
[1] "example_raster_a.tif" "example_raster_b.tif" "example_raster_c.tif" "example_raster_1.tif"
[5] "example_raster_2.tif" "example_raster_3.tif"
The files that I want to select all finish with a numerical value but I do not know how to do it
This may be a trivial question but I'm not used to use string functions and I did not manage to find the information online
CodePudding user response:
A possible solution:
strings <- c("example_raster_a.tif","example_raster_b.tif","example_raster_c.tif","example_raster_1.tif","example_raster_2.tif","example_raster_3.tif")
strings[grepl("\\d\\.tif", strings)]
#> [1] "example_raster_1.tif" "example_raster_2.tif" "example_raster_3.tif"
CodePudding user response:
You can use regular expressions: https://stat.ethz.ch/R-manual/R-devel/library/base/html/regex.html to select the relevant files.
grep("[0-9] \\.tif", dir(), value = TRUE)
CodePudding user response:
You can use Sys.glob
to match certain file patterns:
print(Sys.glob('./*[0-9].tif'))
output:
[1] "./test_1.tif" "./test_2.tif" "./test_3.tif"
All files:
print(Sys.glob('*.tif'))
output:
[1] "test_1.tif" "test_2.tif" "test_3.tif" "test_a.tif" "test_b.tif"
[6] "test_c.tif"
Less powerful than grep (can't match more complex patterns such as matching any number of digits in a row), but simpler (perhaps).