我正在尝试将大量(> 500)的文本文件转换为shapefile。我可以成功地将单个.csv转换为投影的shapefile。只需加载,清理和导出文本文件,我就可以获得lapply和'for'循环。但是当我在循环中添加转换为shapefile时,代码失败了。以下是我尝试解决问题的方法和相关的错误消息:
library(rgdal)
library(sp)
crs.geo<-CRS("+proj=utm +zone=14 +ellps=GRS80 +datum=NAD83 +units=m +no_defs ") #define projection
coltype=c("character","character","character","numeric","numeric") #define data types for input .csv (x,y UTM coords are columns 4,5)
setwd("C:/.../testdata/out")
all.the.filenames <- list.files(pattern= "\\.csv") #create list of files to batch process
head(exampledata,2)
Point Location Time easting northing
1 Trackpoint 14 S 661117 3762441 12/1/2008 5:57:02 AM 661117 3762441
2 Trackpoint 14 S 661182 3762229 12/1/2008 5:58:02 AM 661182 3762229
names <- substr(all.the.filenames, 1, nchar(all.the.filenames)-4) #clean up file names
for(i in names) {
filepath <- file.path("../out",paste(i,".csv",sep=""))
assign(i, read.table(filepath, colClasses=coltype, header=TRUE, sep=",", na.strings=c("NA","")))
coordinates(i) <- c(4,5) #coords in columns 4,5
proj4string(i) <- crs.geo
writeOGR(i,"C:/Users/Seth/Documents/testdata/out","*",driver="ESRI Shapefile") }
R返回此错误消息:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘coordinates<-’ for signature ‘"character"’
如果我在'assign'行之后结束'for'循环,它会成功地将所有.csv文件作为R中的单独对象导入。问题似乎是函数'coordinates'没有将coords视为数字,并且我得到相同的错误消息,无论我如何明确地尝试定义它们(例如,coordinates(i) <- c(as.numeric("easting","northing"))
此外,这些代码行在应用于单个.csv文件时成功运行,问题是当我在a循环。
files.to.process <- lapply(all.the.filenames, function(x) read.csv(x, colClasses=coltype, header=TRUE))
lapply(files.to.process, function(c) coordinates(c)<-c("easting","northing"))
[[1]]
[1] "easting" "northing"
[[2]]
[1] "easting" "northing"
[[3]]
[1] "easting" "northing"
[[4]]
[1] "easting" "northing"
[[5]]
[1] "easting" "northing"
lapply(files.to.process, function(p) proj4string(p) <- crs.geo)
返回错误消息:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘proj4string<-’ for signature ‘"data.frame", "CRS"’
#Double-check if function 'coordinates' worked
class(files.to.process) == "SpatialPoints"
[1] FALSE
使用这两种方法,问题似乎是在'坐标'步骤中制作空间对象。我在循环中做错了什么?非常感谢您的帮助! Seth H.
答案 0 :(得分:0)
在第一次尝试中,循环内的对象是一个角色对象。所以,
False
会更好;我没有一批csv文件来测试它。 在使用lapply()的第二次尝试中,我不确定发生了什么,但是
coordinates(get(i))
应该是“list”,所以你想要做的是
class(files.to.process)
这将告诉您对象是否属于类空间点。我猜他们是data.frames,你需要再介入一步。