【问题标题】:Aggregating all SpatialPolygonsDataFrame objects from list into one SpatialPolygonsDataFrame将列表中的所有 SpatialPolygonsDataFrame 对象聚合到一个 SpatialPolygonsDataFrame
【发布时间】:2018-10-15 16:45:18
【问题描述】:

不打算编辑拓扑,只是将所有多边形聚合成一个sp 类型为SpatialPolygonsDataFrame (spdf) 的对象。每个 spdf 只有一个多边形。

数据 (dropbox link to data)(文件大小 1.1KB)(dput() 在这种情况下不合适):

list_of_spdf <- unlist(readRDS("data.Rds"))

我得到了想要的结果:

one_spdf <- rbind(list_of_spdf[1][[1]], list_of_spdf[2][[1]], list_of_spdf[3][[1]], makeUniqueIDs = TRUE)

# when plotting can see two polygons (third object is a repeat for sake of testing)
plot(one_spdf)

拥有数百个对象(尽管每个 spdf 只有一个多边形),我需要以编程方式执行 rbind。所以我尝试了lapply

list_of_spdf <- lapply(list_of_spdf, rbind, makeUniqueIDs = TRUE)

显然,这会返回一个列表,因此不是我要查找的内容。

于是我写了一个函数:

rbindSPDF <- function(lst) {
# Create empty spdf objects  
pol <-
    SpatialPolygonsDataFrame(SpatialPolygons(list()), data = data.frame())
  pols <-
    SpatialPolygonsDataFrame(SpatialPolygons(list()), data = data.frame())
# loop for rbind
  for (i in 1:length(lst)) {
    pol[i] <- lst[i][[1]]
    if (length(pols) == 0) {
      pols <- pol[i]
    } else {
      pols <- rbind(pols, pol[i], makeUniqueIDs = TRUE)
    }
  }
  return(pols)
}

但是,当使用rbindSPDF:

single_spdf <- rbindSPDF(list_of_spdf)

我明白了:

Error in as.vector(data) : 
 no method for coercing this S4 class to a vector

不知道我在这里做错了什么。

另外,我猜我可能甚至不需要使用自己的函数。

注意:在许多其他软件包之上,我使用 sprgdal 来获取空间数据,并且由于附加/分离时间和掩蔽,我宁愿避免使用另一个软件包。

【问题讨论】:

    标签: r rbind sp spdf


    【解决方案1】:

    要有一个程序化的版本

    one_spdf <- rbind(list_of_spdf[1][[1]], 
                      list_of_spdf[2][[1]], 
                      list_of_spdf[3][[1]], 
                      ...
                      makeUniqueIDs = TRUE)
    

    对于list_of_spdf 中的一个很长的列表,是否可以使用以下方法?

    # generate list containing list_of_spdf[i][[1]]
    list.df <- lapply(seq_along(list_of_spdf),
                      function(i){list_of_spdf[i][[1]]})
    
    # apply rbind to the list
    one_spdf2 <- do.call("rbind",
                         c(args = list.df, makeUniqueIDs = TRUE))
    
    > all.equal(one_spdf, one_spdf2)
    [1] TRUE
    

    结果在我的机器上看起来是一样的。

    【讨论】:

    • 谢谢@Z.Lin。如果我可以将makeUniqueIDs = TRUE 添加到do.call(),我想它可能会起作用。我将如何实现这一目标?
    • 嗯,do.call("rbind", args = c(list.df, makeUniqueIDs = TRUE)) 适合你吗?
    • 知道了,谢谢:one_spdf &lt;- do.call("rbind", c(args = list.df, makeUniqueIDs = TRUE))
    猜你喜欢
    • 2017-03-30
    • 2016-05-28
    • 2018-04-04
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 2015-11-19
    相关资源
    最近更新 更多