readOGR()无法打开文件。

35
wmap <- readOGR(dsn="~/R/funwithR/data/ne_110m_land", layer="ne_110m_land")

这段代码没有加载形状文件,会生成错误

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

我确定目录是正确的。末尾也没有 /,图层名称也是正确的。

在ne_110m_land目录中,我拥有以下文件:

ne_110m_land.dbf
ne_110m_land.prj
ne_110m_land.shp
ne_110m_land.shx
ne_110m_land.VERSION.txt
ne_110m_land.README.html
8个回答

66

你可以通过以下方式表明你走在正确的道路上:

list.files('~/R/funwithR/data/ne_110m_land', pattern='\\.shp$')
file.exists('~/R/funwithR/data/ne_110m_land/ne_110m_land.shp')

也许尝试一下:

readOGR(dsn=path.expand("~/R/funwithR/data/ne_110m_land"), layer="ne_110m_land")

或者一个更简单的替代方案,可以围绕着它:

library(raster)
s <- shapefile("~/R/funwithR/data/ne_110m_land/ne_110m_land.shp")

更新:

rgdal已有所更改,您不再需要分离路径和图层(至少对于某些格式而言)。因此您可以执行以下操作:

x <- readOGR("~/R/funwithR/data/ne_110m_land/ne_110m_land.shp")

(也许仍然使用path.expand)

如果你仍在使用readOGR,那么你有点落后了。更好的选择是使用terra::vectsf::st_read


2
谢谢!path.expand() 工作正常。很抱歉我不能为答案投票。 - Ritesh Jung Thapa
@RiteshJungThapa 你可以接受这个回答为正确答案(即使你不能点赞) - geneorama
为什么问题中发布的代码无法工作?我遇到了同样的问题,但是文件夹中有多个具有相同名称但不同扩展名的文件,因此 path.expand 无法正常工作。 - Dambo
它无法工作是因为readOGR没有使用path.expand,因为它不知道第一个参数实际上是否是文件路径(它可能是数据库)。这对你来说应该没有问题。 - Robert Hijmans
在我的情况下,如果我只使用相对路径,那么上面的代码只能工作一部分,会出现相同的错误。但是如果我添加绝对路径,则可以正常运行。 - JessicaRjes

13

我遇到了同样的错误。要读取shapefile文件,你需要在文件夹中有三个文件:.shp、.dbf和.shx文件。


我和楼主遇到了同样的问题,这个解决方案直接指向了问题所在。 - r0bt

8
对我来说,当我包含dsn和layer标签时,该命令返回“无法打开图层”错误。所以当我将所有内容都包含在内,如下所示: readOGR('~/R/funwithR/data/ne_110m_land/ne_110m_land.shp') 它起作用了。
请注意,我的文件是gjson格式的,因此我只在 readOGR('~/R/funwithR/data/ne_110m_land/ne_110m_land.gjson')中看到这种情况。

2

强制性文件应全部放在同一目录中

.shp — shape格式

.shx — shape索引格式;

.dbf — 属性格式;

然后我们只需将路径作为函数的参数传递即可。

global_24h =readOGR( '/Users/m-store/Desktop/R_Programing/global_24h.shp')

1
你的回答可以通过添加更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

1
语法:library(raster) s <- shapefile(“〜/ R / funwithR / data / ne_110m_land / ne_110m_land.shp”)运行完美!todah rabah!

1
这是我使用的方法(带有真实示例):
require(rgdal)
shape <- readOGR(dsn = "1259030001_ste11aaust_shape/STE11aAust.shp", layer = "STE11aAust")

准确的数据可以在此处获取(下载名为“State and Territory ASGC Ed 2011 Digital Boundaries in MapInfo Interchange Format”的.zip文件)。

0

正如我在其他帖子中所评论的(打开shapefile时出错),使用file.choose()并手动选择将有助于在需要一个文件选择的情况下解决问题。显然与NaturalEarth shapefiles有关


0

在上传到云端之前,对我来说这似乎是解决方案。

  ######################################
  #             Server
  ######################################
  #I tell R where to extract the data from
  #Le digo al R donde debe jalar la data

  dirmapas <- "E:/Tu-carpeta/Tu-sub-carpeta/ESRI" #Depende donde tengas tú tus 
                                                  #archivos de cartografía 

  setwd(dirmapas)

  #The raw map
  # El mapa de polígonos en blanco y negro
  departamentos<-readOGR(dsn="BAS_LIM_DEPARTAMENTO.shp", layer="BAS_LIM_DEPARTAMENTO")

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