user2113499
user2113499

Reputation: 1021

Reading multiple files into R

I have a directory with 365 tif images. Using R, I need to read them in then use a new projection on them then write them as tif files. Basically I have a file full of images and I need to read them in, do some kind of process on them then send them to another file location.

What I have so far is

newproj <- '+init=epsg:4326 +proj=longlat +ellps=WGS84 +datum=WGS84     
+no_defs +towgs84=0,0,0'

x <- dir(path='c:/users/JDD/desktop/process', pattern='.tif')

for(i in 1:length(x)){
temp_i <- raster(x[i])
temp_i <- projectRaster(temp_i, crs=newproj)
writeRaster(temp_i, '2013_i.tif', GTiff)

}

I know working with rasters would normally be asked on the GIS site but my question is with the coding so I hope it is fine here. Any suggestions would be great. Thanks!

Upvotes: 1

Views: 1006

Answers (1)

Mike.Gahan
Mike.Gahan

Reputation: 4615

One approach is to make a function and lapply through all the files in your working directory.

change.proj <- function(x) {
   require(rgdal)
   temp <- raster(x)
   temp <- spTransform(x, crs=CRS(newproj))
   writeRaster(temp, paste0("new",x), GTiff)
}

setwd("your folder with all the tif files")
files = list.files(pattern="*.tif")
lapply(files, function(x) change.proj(x))

I think there is a function called spTransform from the rgdal package that should also do the trick. I am not familar with the projectRaster function.

Upvotes: 1

Related Questions