在R中循环中裁剪shapefile

时间:2016-03-11 16:55:16

标签: r gis

我有大量的shapefiles,各种大小,因为它们代表不同的物种分布。我试图遍历所有这些shapefiles并通过这些shapefiles裁剪其他光栅文件(BioClim变量)。似乎我的问题是由shapefiles本身引起的。我试过堆叠,但这不起作用。鉴于我缺乏在循环中使用shapefiles的经验,任何人都可以深入了解为什么下面提供的代码子集不起作用吗?

library(raster)
library (sp)
library(rgeos)
library(rgdal)
library (raster)
library (maps)
library (mapproj)
library(sp)
library(maptools)

raster("alt.bil") -> alt
raster("bio_1.bil") -> bio1

shape.files=list.files(path="PathToFolderWithShapefiles", pattern="*.shp", full.names=T, recursive=FALSE)


lapply(shape.files, function(x){
    masking= altc = crop(alt, shape.files)
    bio1 = crop(bio1, shape.files)
setwd("/Volumes/LaCie/LoopTestOutput")
writeRaster(altc, filename="alt.asc", bylayer=T, overwrite=FALSE)
writeRaster(bio1, filename="bio1.asc", bylayer=T, overwrite=FALSE)
})

下面是一组适用于单个特定shapefile的代码。我基本上想要在文件夹中的所有shapefile中循环裁剪功能并输出裁剪的光栅文件。

require(raster)
library (sp)
install.packages('rgeos',repos="http://www.stats.ox.ac.uk/pub/RWin")
install.packages('rgdal',repos="http://www.stats.ox.ac.uk/pub/RWin")
library (raster)
library (maps)
library (mapproj)
library(sp)
library(maptools)

setwd("PathToGlobalRasterLayers")

raster("alt.bil") -> alt
raster("bio_1.bil") -> bio1

setwd("PathTofolderContainingSpeciesDelimitedShapefiles")#all files necessary for working with shapefiles are here, .shp, .dbf, etc.#
mask <- readShapeSpatial("ReadInSpeciesDelimitedShapefile")

altc = crop(alt, mask)
bio1 = crop(bio1, mask)


setwd("OutputFolderForCroppedFiles")

writeRaster(altc, filename="alt.asc", bylayer=T, overwrite=TRUE)
writeRaster(bio1, filename="bio1.asc", bylayer=T, overwrite=TRUE)

1 个答案:

答案 0 :(得分:0)

在您的第一个代码块中,您似乎忘记了运行 masking = readShapeSpatial(x)

另外,不要使用setwd(),只需将路径放在filename=参数中即可。这将使您的代码更加明确和可读。