使用readOGR和readShapePoly读取shape文件的区别

14

我使用maptools包中的readShapePoly函数读取了一个shapefile文件,但无法使用readOGR函数读取同一文件。我希望有人能帮助我使用readOGR函数读取这个shapefile文件。

我从这里下载了文件orcounty.shphttp://geography.uoregon.edu/geogr/topics/maps.htm

我还下载了相关文件:orcounty.shxorcounty.sbxorcounty.sbnorcounty.dbf,并将这五个文件放在文件夹中:c:/users/mark w miller/gis_in_R/shapefile_example/

以下代码读取该shapefile文件并显示一些属性:

library(maptools)

setwd('c:/users/mark w miller/gis_in_R/shapefile_example/')

# Oregon county census data (polygons)
orcounty.poly <- readShapePoly('orcounty.shp', proj4string=CRS("+proj=longlat"))
orcounty.line <- readShapeLines('orcounty.shp', proj4string=CRS("+proj=longlat"))

# see projection
summary(orcounty.poly)

Object of class SpatialPolygonsDataFrame
Coordinates:
         min        max
x -124.55840 -116.46944
y   41.98779   46.23626
Is projected: FALSE 
proj4string : [+proj=longlat]
Data attributes:

然而,当我尝试使用以下代码读取相同的shapefile时,我收到了一个错误:

library(rgdal)

# read shapefile
oregon.map <- readOGR(dsn="c:/users/mark w miller/gis_in_R/shapefile_example/", layer="orcounty")

# convert to dataframe
oregon.map_df <- fortify(oregon.map)

错误信息显示:

Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv) : 
  Cannot open file

我可以使用以下方式读取Natural Earth的shapefiles:

library(rgdal)

setwd("c:/users/mark w miller/gis_in_R/")

# read shapefile
wmap <- readOGR(dsn="ne_110m_physical", layer="ne_110m_land")

所以,显然自然地球的shapefile和Oregon的shapefile orcounty.shp之间存在差异。

感谢任何有关如何使用readOGR读取orcounty.shp的建议。我的问题类似于这里的问题:rgdal / readOGR - 无法从.zip文件中读取shapefile


1
我可以正常打开它。尝试使用readOGR(dsn = 'c:/users/mark w miller/gis_in_R/shapefile_example', layer = 'orcounty') - Paulo E. Cardoso
@PauloCardoso 那个方法有效!我简直不敢相信问题的解决方案如此简单。如果你想把它发表成回答,我可以接受它,或者我也可以删除这个问题。 - Mark Miller
4个回答

18

尝试从文件路径中删除最后一个'/'。

readOGR(dsn = 'c:/users/mark w miller/gis_in_R/shapefile_example',
        layer = 'orcounty')

3

如果有人在Linux系统中遇到这个错误,我发现问题出在使用了主目录的快捷方式。例如:

# Works
readOGR(dsn="/home/user/dir", layer="file")

# Doesn't work
readOGR(dsn="~/dir", layer="file")

我不知道为什么。


1
波浪线表达式(~)通常由Unix shell扩展。如果您将其传递到R库调用中,它可能会被按字面意义读取。 - Josip Rodin
1
好的,谢谢。通常在R中,用于读取文件、设置工作目录等操作都是有效的。但在这种情况下,它没有起作用。 - MikeRSpencer

1

我使用了文件 ne_110m_land

请尝试以下内容:

setwd('D:/JMSR/codes.R/mapas')
unzip("ne_110m_land.zip")
ogrInfo(".", "ne_110m_land")
wmap <- readOGR(".", "ne_110m_land")

0

raster::shapefile 包装了 readOGR 并处理了路径和波浪号,只需传递完整的文件名即可。

 library(raster)
 x <- shapefile("c:/users/orcounty.shp')

或者

 y <- shapefile("~/users/orcounty.shp")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接