I am using Bivand
's book to try an figure out how to use R for spatial data but struggling.
I have folder with annual tiff
files for the years 1950 through 2010 (name: tas_mean_C_cru_TS31_01_1950
, columns 4762, rows 2557, source type continuous, pixel type floating point, pixel depth 32 bit, compression LZW).
I want to clip them with a polygon layer and then put the clipped rasters in a new folder with the same name as the original raster. I have code below that I have tried to manipulate from examples in the book and online, but it does not work. My problem comes at the loop section and I get an error at the end.
My two questions are: 1) What is wrong with my loop statement? I am trying to loop through the files in the folder defined in input.path. 2) If I take a step back and ignore the clipping, how can I get the files to be copied and placed in a new folder with the same name?
Thanks Jen
#load libraries
library (sp)
library (rgdal)
library (raster)
library (maps)
library (mapproj)
#SET THE WORKING DIRECTORY PATH
input.path = "F:/Dropbox/GIS/SNAP/Temp/tas50_09/"
#SET THE OUTPUT DIRECTORY
out.file<-"F:/temp/"
#FIND THE SIZE OF THE MATRIX -- WILL NEED THESE TO PRE-ALLOCATE SUBSEQUENT MATRICES
nrow <- 2557
ncol <- 4762
# initial rasters are....
# xmn=-2173225.11814296,xmx= 1498276.88185705, ymn = 409671.150470569,
# ymx = 2381118.15047057, crs = '+proj=aea +lat_1=55 +lat_2=65 +lat_0=50 +lon_0=-154 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs')
# polygon to clip rasters
poly<-readOGR("F:/Dropbox/GIS/AKCommunities","AleutianComm50mile")
#reads the path to the files with a tif extention
file.names <- dir(input.path, pattern =".tif")
# then a loop for reading each existing file of type ".tif" as table
for(j in 1:length(input.path)){
v <- extract(input.path, poly, weights=TRUE, cellnumbers=TRUE)
#Write the data to a geotiff
out <- raster(v ,xmn=-1446037.8545397,xmx= -686037.854539692, ymn = 356262.979377343, ymx = 607262.979377344, crs = '+proj=aea +lat_1=55 +lat_2=65 +lat_0=50 +lon_0=-154 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs')
writeRaster(v,filename=paste(out.file,'file.names ',sep=''),format = 'GTiff',options='COMPRESS=LZW',datatype='FLT4S',overwrite=T)
}
# I get the following error
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘extract’ for signature ‘"character", "SpatialPolygonsDataFrame"’