1# Author: Robert J. Hijmans 2# Date : November 2011 3# Version 1.0 4# Licence GPL v3 5 6 7 8setMethod('union', signature(x='SpatialPolygons', y='SpatialPolygons'), 9function(x, y) { 10 11 valgeos <- .checkGEOS(); on.exit(rgeos::set_RGEOS_CheckValidity(valgeos)) 12 13 x <- sp::spChFIDs(x, as.character(1:length(x))) 14 y <- sp::spChFIDs(y, as.character(1:length(y))) 15 16 prj <- x@proj4string 17 if (is.na(prj)) prj <- y@proj4string 18 x@proj4string <- .CRS(as.character(NA)) 19 y@proj4string <- .CRS(as.character(NA)) 20 21 subs <- rgeos::gIntersects(x, y, byid=TRUE) 22 23 if (!any(subs)) { 24 25 x <- bind(x, y) 26 27 } else { 28 29 xdata <-.hasSlot(x, 'data') 30 ydata <-.hasSlot(y, 'data') 31 if (xdata & ydata) { 32 nms <- .goodNames(c(colnames(x@data), colnames(y@data))) 33 colnames(x@data) <- nms[1:ncol(x@data)] 34 colnames(y@data) <- nms[(ncol(x@data)+1):length(nms)] 35 } 36 37 dif1 <- erase(x, y) 38 dif2 <- erase(y, x) 39 40 x <- intersect(x, y) 41 x <- list(dif1, dif2, x) 42 x <- x[!sapply(x, is.null)] 43 44 i <- sapply(x, length) > 0 45 x <- x[ i ] 46 if (length(x) > 1) { 47 x <- do.call(bind, x) 48 } else { 49 x <- x[[1]] 50 } 51 } 52 if (inherits(x, "Spatial")) { x@proj4string <- prj } 53 x 54} 55) 56 57 58 59 60setMethod('union', signature(x='SpatialPolygons', y='missing'), 61function(x, y) { 62 63 valgeos <- .checkGEOS(); on.exit(rgeos::set_RGEOS_CheckValidity(valgeos)) 64 n <- length(x) 65 if (n < 2) { 66 return(x) 67 } 68 69 prj <- x@proj4string 70 x@proj4string <- .CRS(as.character(NA)) 71 72 #if (!rgeos::gIntersects(x)) { 73 # this is a useful test, but returned topologyerrors 74 # return(x) 75 #} 76 77 if (.hasSlot(x, 'data')) { 78 x <- as(x, 'SpatialPolygons') 79 } 80 81 x <- sp::spChFIDs(x, as.character(1:length(x))) 82 x <- sp::SpatialPolygonsDataFrame(x, data.frame(ID=1:n)) 83 84 u <- x[1,] 85 names(u) <- 'ID.1' 86 for (i in 2:n) { 87 z <- x[i, ] 88 names(z) <- paste('ID.', i, sep='') 89 u <- union(u, z) 90 } 91 92 u@data[!is.na(u@data)] <- 1 93 u@data[is.na(u@data)] <- 0 94 u$count <- rowSums(u@data) 95 u@proj4string <- prj 96 u 97} 98) 99 100setMethod('union', signature(x='SpatialPoints', y='SpatialPoints'), 101function(x, y) { 102 bind(x,y) 103}) 104 105setMethod('union', signature(x='SpatialLines', y='SpatialLines'), 106function(x, y) { 107 bind(x,y) 108}) 109 110 111