Debian Codegraph @

R/aggregate.R

raw
1 aggregate.data.frame.SP <- function (x, by, FUN, ..., dissolve = TRUE) {
2
3 # EP added:
4 stopifnot(is(x, "Spatial"))
5 stopifnot("data" %in% slotNames(x))
6 geom = geometry(x)
7 x = x@data
8
9 stopifnot(NROW(x) > 0L)
10 stopifnot(NCOL(x) > 0L)
11 FUN <- match.fun(FUN)
12
13 # next: fragment taken from stats::aggregate.data.frame, in
14 # R 3.2.4, svn 70336, to find grp
15 if (!is.list(by))
16 stop("'by' must be a list")
17 if (is.null(names(by)) && length(by))
18 names(by) <- paste("Group", seq_along(by), sep = ".")
19 else {
20 nam <- names(by)
21 ind <- which(!nzchar(nam))
22 names(by)[ind] <- paste("Group", ind, sep = ".")
23 }
24 nrx <- NROW(x)
25 # if (any(lengths(by) != nrx))
26 if (any(sapply(by, length) != nrx))
27 stop("arguments must have same length")
28 y <- as.data.frame(by, stringsAsFactors = FALSE)
29 keep <- complete.cases(by)
30 y <- y[keep, , drop = FALSE]
31 x <- x[keep, , drop = FALSE]
32 nrx <- NROW(x)
33 ident <- function(x) {
34 y <- as.integer(as.factor(x))
35 z <- gsub(" ", "0", format(y, scientific = FALSE))
36 return(z)
37 }
38 grp <- if (ncol(y)) {
39 grp <- lapply(rev(y), ident)
40 names(grp) <- NULL
41 do.call(paste, c(grp, list(sep = ".")))
42 } else integer(nrx)
43
44 # let aggregate.data.frame do the attribute work:
45 y = aggregate(x, by, FUN, ..., simplify = TRUE)
46
47 # original would now return y; I added:
48 if (dissolve) { # dissolve/merge:
49 if (!gridded(geom) && is(geom, "SpatialPoints"))
50 geom = split(geom, factor(grp)) # creates SpatialMultiPoints
51 else {
52 warning("No rgeos support in sp from October 2023;\nsee https://r-spatial.org/r/2023/05/15/evolution4.html")
53 .Deprecated("sf::agregate")
54 # if (!requireNamespace("rgeos", quietly = TRUE))
55 stop("use sf::aggregate or terra::aggregate")
56 # if (is(geom, "SpatialLines"))
57 # geom = rgeos::gLineMerge(geom, grp)
58 # else {
59 # if (gridded(geom))
60 # geom = as(geom, "SpatialPolygons")
61 # geom = rgeos::gUnaryUnion(geom, grp)
62 # }
63 }
64 } else
65 y = y[as.integer(factor(grp)),,drop=FALSE] # repeat
66 addAttrToGeom(geom, y, match.ID = FALSE)
67 }
68
69 aggregate.Spatial = function(x, by = list(ID = rep(1, length(x))), FUN, ...,
70 dissolve = TRUE, areaWeighted = FALSE) {
71 if (is(by, "Spatial")) { # maybe better do S4 method dispatch?
72 by0 = by
73 if (gridded(by))
74 by = as(by, "SpatialPolygons")
75 if (is(x, "SpatialPolygonsDataFrame") && is(by, "SpatialPolygons") && areaWeighted) {
76 .Deprecated("sf::agregate")
77 if (!missing(FUN))
78 warning("argument FUN is ignored in area-weighted aggregation, see documentation")
79 df = aggregatePolyWeighted(x, by)
80 } else {
81 FUN <- match.fun(FUN)
82 df = over(by, x, fn = FUN, ...)
83 }
84 addAttrToGeom(by0, df, match.ID = FALSE)
85 } else
86 aggregate.data.frame.SP(x, by, FUN, ..., dissolve = dissolve)
87 }
88
89 aggregatePolyWeighted = function(x, by) {
90 warning("No rgeos support in sp from October 2023;\nsee https://r-spatial.org/r/2023/05/15/evolution4.html")
91 # if (!requireNamespace("rgeos", quietly = TRUE))
92 stop("use sf or terra functions")
93 # i = rgeos::gIntersection(x, by, byid = TRUE, drop_lower_td = TRUE)
94 i = NULL
95 area = sapply(i@polygons, function(x) slot(x, name = "area"))
96 ids.i = sapply(i@polygons, function(x) slot(x, name = "ID"))
97 IDs = strsplit(ids.i, " ") # IDs, as list
98 if (any(sapply(IDs, length) != 2)) # sanity check:
99 stop("IDs contain spaces: this breaks identification after gIntersection()")
100 grp = do.call(rbind, IDs) # IDs matrix; col 1 = x, col 2 = by
101 obs = x[grp[, 1], ]@data # match by IDs of x: get the attributes to aggregate
102 if (all(sapply(obs, is.factor))) { # find level with largest area ...
103 obs$aReA = area
104 spl = split(obs, grp[,2]) # grouped by `by'
105 ret = do.call(rbind, lapply(spl, function(x) x[which.max(x$aReA),])) # take mode
106 ret$aReA = NULL # clean up
107 ret[match(row.names(by), row.names(ret)), , drop=FALSE] # match to by's order
108 } else {
109 if(any(sapply(obs, is.factor)))
110 warning("for factor aggregation, provide factor only data")
111 x_area = data.frame(lapply(obs, function(x) x * area))
112 agg = aggregate(data.frame(area, x_area), list(grp[,2]), sum)
113 ret = data.frame(lapply(agg[-(1:2)], function(x) x / agg$area))
114 ret[match(row.names(by), agg$Group.1), , drop=FALSE]
115 }
116 }