Created
October 2, 2014 18:58
-
-
Save dholstius/8d1aa85a1623243f8f1f to your computer and use it in GitHub Desktop.
Merge a SpatialPolygonsDataFrame with a data.frame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
merge.SpatialPolygonsDataFrame <- function (x, y, by, ...) { | |
require(sp) | |
y <- as.data.frame(y) | |
if (missing(by)) { | |
if (is.null(row.names(x@data)) || is.null(row.names(y))) { | |
warning("[merge.SpatialPolygonsDataFrame] merging by position") | |
i <- 1:nrow(x@data) | |
} else { | |
warning("[merge.SpatialPolygonsDataFrame] merging by row names") | |
i <- row.names(x@data) | |
} | |
} else { | |
message("[merge.SpatialPolygonsDataFrame] merging by ", by) | |
i <- match(x@data[,by], y[,by]) | |
} | |
new_data <- data.frame(x@data, y[i,]) | |
row.names(new_data) <- row.names(x@data) | |
SpatialPolygonsDataFrame(geometry(x), new_data) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment