Reputation: 211
I'm trying to apply a simple function from R program Raster through GeoTIFF files divided into folders.
My files are organized in a folder called 'GeoTIFFs' with subfolders called 'a1', 'a2'...etc. My goal is to go through each file and change all the raster values of 3 to a value of 1 for every .tif file in the GeoTIFFs folder.
This is some code I've written so far. There are a lot of problems with it.
I know I'm supposed to provide example data, but I have no idea how to mimic raster files within folders, which is the essence of my problem.
library(raster)
files = dir('./GeoTIFFs', pattern = '.tif', recursive = TRUE, full.names = TRUE))
nr <- vector("list", length(files))
names(nr) <- files
for (i in 1:length(files)) {
tmp <- raster(files[i])
df <- data.frame(id=3, v=1)
nr[[i]] <- subs(tmp, df, subsWithNA=FALSE)}
This code successfully imports all my files (n=370) but it stops immediately at the for
loop with this error:
Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer", :
Cannot create a RasterLayer object from this file. (file does not exist)
I'm pretty sure this is because R thinks the file name is 'a1/geotiff_example.tif'
instead of 'geotiff_example.tif'
. I also think the rest of the code probably doesn't work (with the exception of the substitution function, which should), so I'd love advice on how to go about this (arguably pretty simple) task. Thanks so much.
Upvotes: 0
Views: 298
Reputation: 94212
Your files don't have the full path with the GeoTIFFs
part:
> files = dir('./GeoTIFFs', pattern = '.tif')
> files
[1] "bar.tif" "foo.tif"
use full.names=TRUE
:
> files = dir('./GeoTIFFs', pattern = '.tif', full.names=TRUE)
> files
[1] "./GeoTIFFs/bar.tif" "./GeoTIFFs/foo.tif"
>
Use the full paths to load the tif into a raster.
If you want to get the last filename part of the path (which is how you are naming your list if I read your code right) then use basename
:
> basename(files)
[1] "bar.tif" "foo.tif"
Upvotes: 2