使用循环在shapefile和数据框之间进行空间连接

时间:2015-08-11 11:47:31

标签: r geospatial spatial sp

我有一个多边形形状文件和一系列数据框。 我想要做的事情是创建一个循环来实现空间加入'在shape文件和所有这些数据框之间,但我一直收到错误。关于这个的任何想法?

这是我的循环代码

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) 

1 个答案:

答案 0 :(得分:0)

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

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