使用循环在shapefile和数据帧之间建立空间连接



我有一个多边形形状文件和一系列数据帧。我想做的是创建一个循环,将使形状文件和所有这些数据帧之间的"空间连接",但我一直得到一个错误。对此有什么想法吗?

下面是我的循环

的代码
datasets <- c("df1","df2","df3")
for (i in datasets){
     gridpolygon <- sp::merge(gridpolygon, i, by = "id", sort = FALSE) #Spatial Join
     }
> Error in table(y[, by.y]) : attempt to set an attribute on NULL

下面是一个可重复的例子,分为三个步骤。

(1)从随机多边形

创建正则网格多边形
# Load libraries
library(sp)
library(rgdal)
library(rgdal)
library(raster)
library(rgeos)
library(dismo)
library(data.table)
### create a regular gridded polygon from a random polygon 
# create polygon Random Polygon
    set.seed(1)
    dat <- matrix(stats::rnorm(2000), ncol = 2)
    ch <- chull(dat)
    coords <- dat[c(ch, ch[1]), ]  # closed polygon
    sp_poly <- SpatialPolygons(list(Polygons(list(Polygon(coords)), ID=1)))
    plot(sp_poly)
# create a regular gridded polygon
    # Create an empty raster
    grid <- raster(extent(sp_poly))
    # Choose its resolution.
    res(grid) <- 1 
    # coordinate reference system 
    proj4string(grid)<-CRS("++proj=utm +zone=48") # set it to UTM
    # Transform this raster into a polygon
    gridpolygon <- rasterToPolygons(grid)
    # Create and ID variable of Grid Cells 
    gridpolygon@data$id = rownames(gridpolygon@data)    
    plot(gridpolygon)
(2)创建数据帧
  df1 <- data.table(id=seq(1:5), x=c(11:15))
  df2 <- data.table(id=seq(1:5), y=c(21:25))
  df3 <- data.table(id=seq(1:5), z=c(31:35))

(3)尝试循环

datasets <- c("df1","df2","df3")
for (i in datasets){
     gridpolygon <- sp::merge(gridpolygon, i, by = "id", sort = FALSE) #Spatial Join
     }
> Error in table(y[, by.y]) : attempt to set an attribute on NULL

如果我一个接一个地进行空间连接,我会得到正确的结果,但这不会解决我的问题,因为我有太多的数据集

# Spatial join, one by one
  gridpolygon <- sp::merge(gridpolygon, df1, by = "id", sort = FALSE) 
  gridpolygon <- sp::merge(gridpolygon, df2, by = "id", sort = FALSE) 
  gridpolygon <- sp::merge(gridpolygon, df3, by = "id", sort = FALSE) 

这是@NicE在评论中提出的解决方案。这只是在循环中使用get(i)而不是i的问题。

  for (i in datasets){
    gridpolygon <- sp::merge(gridpolygon, get(i), by = "id", sort = FALSE)
  }

相关内容

  • 没有找到相关文章

最新更新