【问题标题】:Writing a loop for cliping multiple spatial data frame by a polygon shapefile编写一个循环以通过多边形 shapefile 剪切多个空间数据框
【发布时间】:2015-12-04 19:01:41
【问题描述】:

我已经有一些名为 201101.dbf 到 201412.dbf 的 .dbf 文件,并且研究区 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="/"))}

脚本出现以下错误!

(函数(类,fdef,mtable)中的错误: 无法找到签名“列表”的函数“坐标

【问题讨论】:

  • 可能read.dbf(Data[i]) 没有返回i 之一的data.frame。 sapply(lapply(Data,read.dbf),class) 的结果是什么?
  • 感谢@jlhoward,正如您评论的那样,我注意到错误的根源是什么,我已将文件从 .text 格式导入为 dbf 格式,因此所有内容都在列表中,我必须将它们转换通过此代码到数据框:df <- data.frame(matrix(unlist(l),),stringsAsFactors=FALSE)
  • 如果它们已经是文本格式,为什么不使用read.table(...)read.csv(...)??
  • 亲爱的@jlhoward,是的,你是对的,这可能真的更容易,更省时,我应该通过 Arcmap 执行这个过程,所以我准备了数据框!

标签: r spatial


【解决方案1】:

我发现在这种情况下我不允许使用 gIntersection 函数,而是使用下面写的函数,在这种情况下 gIntersection 剪辑点位置但它不会将变量保留在空间数据框中:

Clip-data=Data2[studyarea, ]

然后我完成代码的循环部分如下:

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

它终于奏效了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2018-08-01
    • 2019-02-22
    相关资源
    最近更新 更多