简体   繁体   中英

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. Now, looking for a way to clip (subset) the dbf files by the shapefile.

#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"'

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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