简体   繁体   English

编写循环以通过多边形shapefile裁剪多个空间数据框

[英]Writing a loop for cliping multiple spatial data frame by a polygon shapefile

I have already some .dbf files named 201101.dbf to 201412.dbf, and the study area shapefile ready. 我已经有一些名为201101.dbf到201412.dbf的.dbf文件,并且研究区域shapefile已经准备就绪。 Now, looking for a way to clip (subset) the dbf files by the shapefile. 现在,寻找一种通过shapefile剪切(子集)dbf文件的方法。

#Loading libraries
library(foreign)
library(maptools)
library(rgdal)
library(rgeos)

#set working directory 
setwd('D:/Data1")

#Load the dbf files
Data=dir(,pattern="dbf")

#load study area shape file 
studyarea=readShapeSpatial("D:/Data1/study-area.shp")

#Setting the projection for study area
proje4string(studyarea)=CRS("+init=epsg:32639")


#Looping
for(i in 1:length(Data)){
Data2=read.dbf(Data[i])

#setting coordinates for dbf files
coordinates(Data2)=~longitude+latitude

#Setting the projection for dbf files
proj4string(Data2)=CRS(proj4string(studyarea))

#Clipping the spatial data frames 
Clip-data=gIntersection(Data2,studyarea,byid=TRUE)

#Writing clipped spatial data frames with the names of original dataframes
write.dbf(Clip-Data,Data2=paste("D:/data", paste("Clip-data",Data[i]), sep="/"))}

I got the following error for the script! 我的脚本出现以下错误!

Error in (function (classes, fdef, mtable) : unable to find an inherited method for function 'coordinates<-' for signature '"list"' 错误(函数(类,fdef,mtable):无法为签名“列表”的函数“ coordinates <-”找到继承的方法

I found out that I am not allowed to use gIntersection function in the case,but over function as written below, in the case gIntersection clips the points locations but it does not keep the variables in the spatialdataframe: 我发现不允许在这种情况下使用gIntersection函数,而是在下面编写的函数上使用,在这种情况下,gIntersection会修剪点的位置,但不会在空间数据框中保留变量:

Clip-data=Data2[studyarea, ]

Then I complete the looping part of the code as below: 然后,我完成了代码的循环部分,如下所示:

#Looping 

for(i in 1:length(Data)){
#reading dataframes
Data2=read.dbf(Data[i])

#Accessing Filename of dataframes in List
Filename=Data[i]


#setting coordinates for the dataframes 
coordinates(Data2)=~longitude+latitude

#Setting the projection 
proj4string(Data2)=CRS(proj4string(studyarea))

#Clipping the spatial data frames 
clipdata=Data2[studyarea, ]

#Defining dsn and layer in writeORG and assigning the original names of dataframes on new derived files

dsn = layer = gsub(".dbf","",Filename)

#writing ESRI Shapefile (spatialpointsdataframe) using Rgdal package. 
writeOGR(clipdata, dsn, layer, driver="ESRI Shapefile")

And it's finally working. 终于可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM