使用 R shapefile 包中的 convert.to.shapefile 将额外的数据列添加到 shapefile

Posted

技术标签:

【中文标题】使用 R shapefile 包中的 convert.to.shapefile 将额外的数据列添加到 shapefile【英文标题】:Adding extra data column to shapefile using convert.to.shapefile in R's shapefiles package 【发布时间】:2014-07-03 08:13:07 【问题描述】:

我的目标很简单,即在 shapefile 中添加 1 列统计数据,以便我可以使用它为地理区域着色。数据是来自 gadm 的国家/地区文件。为此,我通常在 R 中使用外部包:

library(foreign)

newdbf <- read.dbf("CHN_adm1.dbf") #original shape file

incrdata <- read.csv("CHN_test.csv") #.csv file with same region names column + new data column

mergedbf <- merge(newdbf,incrdata)

write.dbf(mergedbf,"CHN_New")

这几乎在所有情况下都可以实现我想要的,但是我正在处理的 R 外部软件之一只能识别 .shp 文件而不会读取 .dbf(尽管从某种意义上说,这种说法很明显矛盾)。不知道为什么它不会。无论如何,本质上它让我需要做与上面相同的事情,但使用 shapefile。我认为根据 shapefiles 包的注释,该过程应该像这样运行:

library(shapefiles)

shaper <- read.shp("CHN_adm1.shp")

simplified <- convert.to.simple(shaper)

simplified <- change.id(simplified,incrdata$DataNew) #DataNew being new column of data from the .csv

simpleAsList <- by(simplified,simplified[,1],function(x)x)

####This is where I hit problems####

backToShape <- convert.to.shapefile(simplified,
              data.frame(index=c("20","30","40","50","60","70","80")),"index",5)

write.shapefile(backToShape,"CHN_TestShape")

恐怕我无法理解 shapefile,因为我无法解开它们或以我可以使用数据框的方式将它们可视化,因此当返回到外部图表包。

要明确:在“backToShape”中,我只想添加数据列并重建 shapefile。碰巧我的数据显示为一个因素,即 20、30、40 等,但数据也可以很容易地连续,我确信我不需要输入所有可能性,但它是我似乎可以让它被接受的唯一方法。有人可以让我走上正确的轨道,如果我错过了更简单的方法,我也会非常感谢听到建议。非常感谢。

【问题讨论】:

【参考方案1】:

停止使用shapefiles 包。

安装 sprgdal 软件包。

使用以下命令读取 shapefile:

chn = readOGR(".","CHN_adm1") # first arg is path, second is shapefile name w/o .shp

现在chn 就像一个数据框。事实上chn@data 是一个数据框。对该数据框执行您喜欢的操作,但保持相同的顺序,然后您可以通过以下方式将更新后的 shapefile 与新数据一起保存:

writeOGR(chn, ".", "CHN_new", driver="ESRI Shapefile")

请注意,您不应该真正直接操作 chn@data 数据框,您可以使用 chn,就像它在许多方面是一个数据框一样,例如 chn$foo 获取名为 foo 的列,或 @如果您有人口和面积列,987654332@ 将创建一个新的人口密度列。

spplot(chn, "popden")

将映射到您刚刚创建的 popden 列,并且:

head(as.data.frame(chn))

应该显示 shapefile 数据的前几行。

【讨论】:

完美。正是我想要的。效果很好,加上另一个图表选项可以很好地衡量。非常感谢!! 阅读“R Spatial Task View”或任何 R Spatial 教程(我的可能在 google 上很受欢迎!) 谢谢,我需要这个。

以上是关于使用 R shapefile 包中的 convert.to.shapefile 将额外的数据列添加到 shapefile的主要内容,如果未能解决你的问题,请参考以下文章

如何使用坐标和 R 中 shapefile 中的另一个值从栅格中提取值?

在 R 中组合多个 shapefile

R:在 shapefile 中的多边形上绘制 .gdb 文件中的点

R:将栅格聚合为 shapefile 多边形

在 R 中结合边界 shapefile

使用 R 将 lat/long 点的数据框空间连接到多边形 shapefil