【问题标题】:Creating Shapefiles in R在 R 中创建形状文件
【发布时间】:2013-04-12 02:51:25
【问题描述】:

我正在尝试在 R 中创建一个 shapefile,稍后将其导入 Fusion Table 或其他一些 GIS 应用程序。

首先,我导入了一个包含加拿大所有人口普查区的空白 shapefile。我已根据 CT 的唯一 ID 将其他数据(以表格格式)附加到 shapefile,并映射了我的结果。目前,我只需要温哥华的那些,我想导出一个仅包含温哥华 CT 以及我新附加的属性数据的 shapefile。

这是我的代码(出于隐私原因省略了某些部分):

shape <- readShapePoly('C:/TEST/blank_ct.shp') #Load blank shapefile
shape@data = data.frame(shape@data, data2[match(shape@data$CTUID, data2$CTUID),]) #data2 is my created attributes that I'm attaching to blank file
shape1 <-shape[shape$CMAUID == 933,] #selecting the Vancouver CTs

我已经看到了使用此方法的其他示例:writePolyShape 来创建 shapefile。我试过了,它在一定程度上奏效了。它创建了 .shp、.dbf 和 .shx 文件。我错过了 .prj 文件,我不确定如何创建它。有没有更好的方法来创建 shapefile?

我们将不胜感激任何有关此事的帮助。

【问题讨论】:

  • 这就是我写文件的方式writeOGR(obj = opno.skupaj.mean[[1]], dsn = "q:/path/to/file/spat_odstrel_skupaj.shp", layer = "spat_odstrel_skupaj", driver = "ESRI Shapefile")。请注意,图层和文件名是相同的(减去.shp)。

标签: r gis shapefile


【解决方案1】:

使用rgdalwriteOGRrgdal 将保留投影信息

类似

library(rdgal)

shape <- readOGR(dsn = 'C:/TEST', layer = 'blank_ct')
# do your processing
shape@data = data.frame(shape@data, data2[match(shape@data$CTUID, data2$CTUID),]) #data2 is my      created attributes that I'm attaching to blank file
shape1 <-shape[shape$CMAUID == 933,]
writeOGR(shape1, dsn = 'C:/TEST', layer ='newstuff', driver = 'ESRI Shapefile')

请注意,dsn 是包含 .shp 文件的文件夹,layer 是不带 .shp 扩展名的 shapefile 的名称。它将读取(readOGR)并写入(writeOGR)所有组件文件(.dbf.shp.prj 等)

【讨论】:

  • 这不会按原样工作,您没有在 writeOGR 调用中指定 shapeshape1 对象 - 它怎么知道要写什么?
  • 我认为writeOGR的dsn路径需要是一个以.shp结尾的完整文件路径。
  • @Roman 不需要,可以是 writeOGR(x, ".", "layername", "ESRI Shapefile") 或 writeOGR(x, "C:/temp/layername.shp" , "layername", "ESRI Shapefile")
  • @mdsumner 哈!我想知道我做错了什么。我无法用你的方法写,但现在它可以工作了。我们是否经常穿越奇怪事情发生的区域?
  • @mdsumner 如果决定不指定完整文件路径,dsn 中的路径不包含尾部斜杠很重要。
【解决方案2】:

问题解决了!再次感谢帮助的人!

这是我最终做的:

正如 Mnel 所写,这一行将创建 shapefile。

writeOGR(shape1, dsn = 'C:/TEST', layer ='newstuff', driver = 'ESRI Shapefile')

但是,当我运行此行时,它返回此错误:

Can't convert columns of class: AsIs; column names: ct2,mprop,mlot,mliv

这是因为我的属性数据不是数字,而是字符。幸运的是,我的属性数据都是数字,所以我运行了 transform() 来解决这个问题。

shape2 <-shape1
shape2@data <- transform(shape1@data, ct2 = as.numeric(ct2),
mprop = as.numeric(mprop),
mlot = as.numeric(mlot),
mliv = as.numeric(mliv))

我再次尝试了 writeOGR() 命令,但仍然没有得到我正在寻找的 .prj 文件。问题是我在导入文件时没有指定 shapefile 的坐标系。由于我已经知道坐标系是什么,我所要做的就是在导入时定义它。

readShapePoly('C:/TEST/blank_ct.shp',proj4string=CRS("+proj=longlat +datum=WGS84")

在那之后,我重新运行了我想要对 shapefile 执行的所有操作,以及用于导出的 writeOGR 行。就是这样!

【讨论】:

    猜你喜欢
    • 2012-10-23
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多