我正在尝试遍历目录中的文件夹,同时读取文件并将其分配给R
.
我想分配给变量的文件是我使用包shapefiles
中的函数。目的是稍后合并属于特定物种的所有 shapefile。目录的层次结构/结构是>> 。外观等。readOGR
rgdal
type1
species
ids
shapefiles
id.shp
#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
.