将额外数据(帧)合并到R中的空间对象可能很棘手(如here所述,或here)
正在寻找有关如何正确完成工作的解决方案,我发现此SO question列出了几种方法。 dplyr
的{{1}}未列在那里。我发现它被用在Robin的tutorial中。
我的问题是 - 这是一种使用的纠正方法吗?是否有任何用例(不同的行数?不同的行名称?排序?等),这种解决方案会失败?
这是一些可重复的代码,说明我发现/遇到的方法:
left_join
左联盟似乎可以胜任。与# libraries
library("spdep"); library("sp"); library("dplyr")
# sopatial data
c <- readShapePoly(system.file("etc/shapes/columbus.shp", package="spdep")[1])
m <- c@data
c@data <- subset(c@data, select = c("POLYID", "INC"))
c@data$INC2 <- c@data$INC
c@data$INC <- NULL
ex <- subset(c, c$POLYID <= 2) # polygons with messed up data in merged df
c <- subset(c, c$POLYID < 49) # remove one polygon from shape so that df has one poly too many
# messing up merge data
m <- subset(m, POLYID != 1) # exclude polygon
m <- subset(m, select = c("POLYID", "INC")) # only two vars
rownames(m) <- m$POLYID - 2 # change rownames
m$POLYID[m$POLYID == 2] <- 0 # wrong ID
m <- m[order(m$INC),] # different sort
m$POLYID2 <- m$POLYID # duplicated to check dplyr
# left_join solution
s1 <- c
s1@data <- left_join(s1@data, m)
plot(c)
plot(s1, col = "red", density = 40, angle = 0, add = TRUE)
plot(ex, col= NA, border = "green", add = TRUE)
View(s1@data)
# match solution
s2 <- c
s2@data = data.frame(s2@data, m[match(s2@data[,"POLYID"], m[,"POLYID"]),])
plot(c)
plot(s2, col = "red", density = 40, angle = 0, add = TRUE)
plot(ex, col= NA, border = "green", add = TRUE)
View(s2@data)
# sp solution
s3 <- c
s3 <- sp::merge(s3, m, by="POLYID")
plot(c)
plot(s3, col = "red", density = 40, angle = 0, add = TRUE)
plot(ex, col= NA, border = "green", add = TRUE)
View(s3@data)
# inner join solution
s4 <- c
s4@data <- inner_join(s4@data, m)
plot(c)
plot(s4, col = "red", density = 40, angle = 0, add = TRUE)
plot(ex, col= NA, border = "green", add = TRUE)
View(s4@data)
# rebuild solution???
s5 <- c
s5.df <- as(s5, "data.frame")
s5.df1 <- merge(s5.df, m, sort=FALSE, by.x="POLYID", by.y="POLYID", all.x=TRUE, all.y=TRUE)
s51 <- SpatialPolygonsDataFrame(as(s5, "SpatialPolygons"), data=s5.df1)
plot(c)
plot(s51, col = "red", density = 40, angle = 0, add = TRUE)
plot(ex, col= NA, border = "green", add = TRUE)
和sp::merge
相同(我希望没有搞乱订单,所以例如在合并后绘制的多边形与不同的vales相关联?)。没有一个解决方案实际上删除了带有数据的两个多边形,但我认为这是R中的正确行为?