| 1 |
# Author: Robert J. Hijmans |
| 2 |
# Date : November 2011 / October 2015 |
| 3 |
# Version 2 |
| 4 |
# Licence GPL v3 |
| 5 |
|
| 6 |
if (!isGeneric("merge")) { |
| 7 |
setGeneric("merge", function(x, y, ...) |
| 8 |
standardGeneric("merge")) |
| 9 |
} |
| 10 |
|
| 11 |
|
| 12 |
setMethod('merge', signature(x='Spatial', y='ANY'), |
| 13 |
function(x, y, ...) { |
| 14 |
y <- try(as.data.frame(y)) |
| 15 |
if (!inherits(y, 'data.frame')) { |
| 16 |
stop('y cannot be coerced to a data.frame') |
| 17 |
} |
| 18 |
merge(x, y) |
| 19 |
} |
| 20 |
) |
| 21 |
|
| 22 |
|
| 23 |
setMethod('merge', signature(x='Spatial', y='data.frame'), |
| 24 |
function(x, y, by=intersect(names(x), names(y)), by.x=by, |
| 25 |
by.y=by, all.x=TRUE, suffixes = c(".x",".y"), |
| 26 |
incomparables = NULL, duplicateGeoms=FALSE, ...) { |
| 27 |
|
| 28 |
if (!('data' %in% slotNames(x))) |
| 29 |
stop('x has no attributes') |
| 30 |
|
| 31 |
|
| 32 |
x$DoNotUse_temp_sequential_ID_963 <- 1:nrow(x) |
| 33 |
d <- merge(x@data, y, by=by, by.x=by.x, by.y=by.y, suffixes=suffixes, |
| 34 |
incomparables=incomparables, all.x=all.x, all.y=FALSE) |
| 35 |
|
| 36 |
if (!all.x) { |
| 37 |
# Spatial* objects cannot have NULL geometries |
| 38 |
if (nrow(d) == 0) { |
| 39 |
warning('no matching records') |
| 40 |
return(NULL) |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
# sort the merged table |
| 45 |
d <- d[order(d$DoNotUse_temp_sequential_ID_963), ] |
| 46 |
|
| 47 |
# Normally we want one-to-one joins with spatial data |
| 48 |
if (!duplicateGeoms) { |
| 49 |
if (any(table(d$DoNotUse_temp_sequential_ID_963) > 1)) { |
| 50 |
stop('non-unique matches detected') |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
# duplicate (duplicateGeoms = TRUE) or remove (all.x=FALSE) records if needed |
| 55 |
x <- x[d$DoNotUse_temp_sequential_ID_963, ] |
| 56 |
|
| 57 |
d$DoNotUse_temp_sequential_ID_963 <- NULL |
| 58 |
x@data <- d |
| 59 |
x |
| 60 |
} |
| 61 |
) |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|