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

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

问题描述

我有(再次)在R中组合数据帧的问题。但是这一次是SpatialPolygonDataFrame( SPDF ),另一个是通常的数据框架( 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)

但这只会导致一个正常的数据框架,而不是一个空格多边形数据框架。
我在别的地方阅读,这不行,但是我不明白在这种情况下该怎么办(必须用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这么难的问题,我想...

oooh such a hard question, I quess...

谢谢!
Jens

Thanks! Jens

推荐答案

让df = data frame,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]),])

这是代码的工作原理。内部匹配函数对齐列,以便保留顺序。所以当我们将它与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)

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

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