0

我正在尝试遍历目录中的文件夹,同时读取文件并将其分配给R.

我想分配给变量的文件是我使用包shapefiles中的函数。目的是稍后合并属于特定物种的所有 shapefile。目录的层次结构/结构是>> 。外观等。readOGRrgdaltype1speciesidsshapefilesid.shp

示例 shapefile 可在此处此处下载

#code
setwd("~/type1/")

#Extract ids belonging to $species. Later use in readOCR function

sp_id <- function(species){
 wd = "~/type1/"
 list_shp <- list.files(path=paste(wd,species,sep='/'), full.names = F, recursive = F, include.dirs = F)
 vec <- character() 

  for (shp in list_shp){
   y <- unlist(strsplit(shp, '\\.', perl=T))
   vec <- unique(c(vec,y[1]))
  }

 #"1905" "4279"

#Extract dirs for where to perform readOCR function

  list_dir <- list.dirs(path=paste(wd,species,sep='/'), full.names = F, recursive = F)

   for (id in list_dir){
    setwd(id)
    print(getwd())
   }

#"~/type1/speciesX1/1905"
#"~/type1/speciesX1/4279"

    for (i in vec){
     assign(paste("", i, sep=""), readOGR(".", i))
    break
    }
 }

sp_id('speciesX1')

[1] "~/type1/speciesX1/1905"
OGR data source with driver: ESRI Shapefile 
Source: ".", layer: "1905"
with 10 features and 3 fields
Feature type: wkbPolygon with 2 dimensions
[1] "~/type1/speciesX1/4279"
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv) : 
Cannot open layer

问题是代码只执行readOGR其中shapefile之一dirs,似乎再次更改 dir 但不执行最后一个readOGR.

4

2 回答 2

2

您的功能似乎在许多不同的部分被破坏,但您可以这样做:

library(rgdal)

setwd("~/type1/")
species <- 'speciesX1'
list_shp <- list.files(path=species, pattern="*.shp", full.names = TRUE,
                       recursive = TRUE, include.dirs = FALSE)
shp_objects <- lapply(list_shp, function(x) {readOGR(dsn=x, 
                                                     layer=ogrListLayers(x))})

这将为您提供SpatialPolygonDataframe随后可以合并的对象列表。

于 2013-12-11T11:26:14.313 回答
0

我无法ogrInfo()读取那些缺少图层错误的文件)。这提供了一种读取和获取某些属性的方法。(Mac 会采用重复的目录名称并将“(n)”附加到它们,因此名称相同但不同的文件是 iho.zip 和 iho.zip:

library(sp)

ca3 = readShapeSpatial("~/Downloads/iho/iho.shp")
ca3 = readShapeSpatial("~/Downloads/iho(2)/iho.shp")

> attributes(ca3)$data
                               name   id mrgid
0 Mediterranean Sea - Western Basin 28Aa  4279
1               Strait of Gibraltar  28a  3346
2                       Alboran Sea  28b  3324
3                      Balearic Sea  28c  3322
4                      Ligurian Sea  28d  3363
5                    Tyrrhenian Sea  28e  3386
> attributes(ca2)$data
                               name   id mrgid
0 Mediterranean Sea - Western Basin 28Aa  4279
1 Mediterranean Sea - Eastern Basin 28Bb  4280
2               Strait of Gibraltar  28a  3346
3                       Alboran Sea  28b  3324
4                      Balearic Sea  28c  3322
5                      Ligurian Sea  28d  3363
6                    Tyrrhenian Sea  28e  3386
7                      Adriatic Sea  28g  3314
8                        Ionian Sea  28f  3351
9                        Aegean Sea  28h  3315
于 2013-12-11T07:28:34.450 回答