【问题标题】:merge data vector to shapefile data slot将数据向量合并到 shapefile 数据槽
【发布时间】:2011-04-20 14:33:34
【问题描述】:

我尝试使用merge 和 2 位 ISO 代码作为 ID 将经济数据添加到 shapefile。代码看起来有点像这样:

library(maptools)
library(foreign)
library(sp)
library(lattice)
library(shapefiles)

world.shp<-readShapePoly("world_shapefile.shp")

world.shp@data<-merge(world.shp@data, data.frame(country=iso.code.vector, net=country.data.vector), by.x="ISO2", by.y="country", all.x=TRUE, sort=FALSE)

不幸的是,即使我输入了sort 参数,这也会破坏 .shp 文件的顺序。之后的图显示数据与应有的多边形不匹配。我做错了什么?

我从thematicmapping.org得到了世界地图数据

感谢您的帮助

【问题讨论】:

    标签: r gis


    【解决方案1】:

    合并总是会破坏 sp 对象。以下是将数据框合并到 sp @data 数据框的两种方法。

    shape@data = data.frame(shape@data, OtherData[match(sdata@data$IDS, OtherData$IDS),])
    

    在哪里; shape 是您的 shape 文件,IDS 是您要合并的标识符,OtherData 是您要与 shape 结合的数据框。请注意,IDS 在两个数据集中可以是不同的名称,但实际上需要是相同的值(不是模糊的)。

    您也可以使用此功能。

    join.sp.df <- function(x, y, xcol, ycol) {
      x$sort_id <- 1:nrow(as(x, "data.frame"))  
        x.dat <- as(x, "data.frame")  
         x.dat2 <- merge(x.dat, y, by.x = xcol, by.y = ycol)  
        x.dat2.ord <- x.dat2[order(x.dat2$sort_id), ]  
      x2 <- x[x$sort_id %in% x.dat2$sort_id, ]  
      x2.dat <- as(x2, "data.frame") 
        row.names(x.dat2.ord) <- row.names(x2.dat)  
      x2@data <- x.dat2.ord  
      return(x2)
    }
    

    在哪里; x=sp SpatialDataFrame object, y=dataframe object to merge with x, xcol=Merge column name in sp object (需要引号), ycol=Merge column name in dataframe object (需要引号)

    【讨论】:

      【解决方案2】:

      我在使用 R 版本 2.12.x 和 2.13.x 时发现了同样的问题,但该问题似乎已在版本 2.15.1 中得到解决。

      【讨论】:

      • 后来发现merge总是会破坏顺序。解决方案是在数据中添加一个新列(称为“索引”),将其从 1 到 n 人为地编号,对原始数据执行您需要执行的操作(合并等),最后对其进行排序根据您的“索引”列返回。
      【解决方案3】:

      我找到了解决方法。实际上不是很优雅,执行需要一些时间,但它有效:

      world.shp<-readShapePoly("world_shapefile.shp")
      
      net<-rep(NA,length(world.shp@data$NAME))
      
      for(i in 1:length(net))
      {
          for(j in 1:length(iso.code.vector))
          {
              if(!is.na(world.shp@data$ISO2[i])){if(world.shp@data$ISO2[i]==iso.code.vector[j]){net[i]=country.data.vector[j]}}
          }
      }
      
      world.shp@data<-data.frame(world.shp@data, net)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-29
        • 1970-01-01
        • 2022-01-20
        • 2020-04-27
        • 1970-01-01
        • 2021-01-16
        • 2023-04-11
        • 1970-01-01
        相关资源
        最近更新 更多