如何将一个简单的 data.frame 附加到 R 中的 SpatialPolygonDataFrame? [英] How to attach a simple data.frame to a SpatialPolygonDataFrame in R?

查看:15
本文介绍了如何将一个简单的 data.frame 附加到 R 中的 SpatialPolygonDataFrame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我(再次)在 R 中组合数据帧时遇到问题.但这一次,一个是 SpatialPolygonDataFrame (SPDF),另一个是通常的 data.frame (DF).SPDF 大约有 1000 行,DF 只有 400 行.两者都有一个共同的列,QDGC

I have (again) a problem with combining data frames in R. But this time, one is a SpatialPolygonDataFrame (SPDF) and the other one is usual data.frame (DF). The SPDF has around 1000 rows the DF only 400. Both have a common column, QDGC

现在,我试过了

oo <- merge(SPDF,DF, by="QDGC", all=T)

但这只会导致正常的 data.frame,不再是空间多边形数据框.我在别处读到,这不起作用,但我不明白在这种情况下该怎么做(必须对 ID 列做一些事情,合并使用)

but this only results in a normal data.frame, not a spatial polygon data frame any more. I read somewhere else, that this does not work, but I did not understand what to do in such a case (has to do something with the ID columns, merge uses)

哦,这么难的问题,我问...

oooh such a hard question, I quess...

谢谢!延斯

推荐答案

令 df = 数据框,sp = 空间多边形对象,by = 公共列的名称或列号.然后,您可以使用以下代码行将数据框合并到 sp 对象中

Let df = data frame, sp = spatial polygon object and by = name or column number of common column. You can then merge the data frame into the sp object using the following line of code

sp@data = data.frame(sp@data, df[match(sp@data[,by], df[,by]),])

这是代码的工作原理.内部的 match 函数对齐列,以便保留顺序.因此,当我们将其与 sp@data 合并时,顺序会被正确保留.快速检查代码是否有效是检查与公共列对应的两列并查看它们是否相同(公共列被复制并且很容易删除副本,但我保留它,因为它是好的检查)

Here is how the code works. The match function inside aligns the columns so that order is preserved. So when we merge it with sp@data, order is correctly preserved. A quick check to see if the code has worked is to inspect the two columns corresponding to the common column and see if they are identical (the common columns get duplicated and it is easy to remove the copy, but i keep it as it is a good check)

这篇关于如何将一个简单的 data.frame 附加到 R 中的 SpatialPolygonDataFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆