Debian Codegraph @

R/SpatialGridDataFrame-methods.R

raw
1 SpatialPixelsDataFrame = function(points, data,
2 tolerance = sqrt(.Machine$double.eps),
3 proj4string = CRS(as.character(NA)), round = NULL, grid = NULL) {
4 if (is.null(points))
5 stop("points argument is NULL")
6 if (is(points, "SpatialPixels") && is.null(grid))
7 grid = points@grid
8 if (!is(points, "SpatialPoints"))
9 points = SpatialPoints(points, proj4string = proj4string)
10 points = SpatialPixels(points, tolerance = tolerance, round = round,
11 grid = grid)
12 new("SpatialPixelsDataFrame", points, data = data)
13 }
14
15 SpatialGridDataFrame = function(grid, data, proj4string = CRS(as.character(NA))) {
16 if (!is(grid, "SpatialGrid"))
17 grid = SpatialGrid(grid, proj4string)
18 new("SpatialGridDataFrame", grid, data = data)
19 }
20
21 setMethod("addAttrToGeom", signature(x = "SpatialPixels", y = "data.frame"),
22 function(x, y, match.ID, ...)
23 SpatialPixelsDataFrame(geometry(x), y, ...)
24 )
25
26 setMethod("addAttrToGeom", signature(x = "SpatialGrid", y = "data.frame"),
27 function(x, y, match.ID, ...)
28 SpatialGridDataFrame(geometry(x), y, ...)
29 )
30
31 as.SPixDF.SGDF = function(from) {
32 data = list()
33 n = .NumberOfCells(from@grid)
34 for (i in seq_along(from@data)) {
35 v = vector(mode(from@data[[i]]), n)
36 if (is.factor(from@data[[i]]))
37 v = factor(rep(NA, n), levels = levels(from@data[[i]]))
38 else
39 v[[email protected]] = NA
40 v[[email protected]] = from@data[[i]]
41 data[[i]] = v
42 }
43 data = data.frame(data, stringsAsFactors = FALSE)
44 names(data) = names(from@data)
45 SpatialGridDataFrame(from@grid, data, rebuild_CRS(slot(from, "proj4string")))
46 }
47 #setAs("SpatialPixelsDataFrame", "SpatialGridDataFrame", as.SPixDF.SGDF)
48
49 # Jon Skoien, Apr 18, 2013:
50 # Version where from@data is first added to data, then the columns with
51 # factors are correctly added in a second step. By far the fastest when
52 # there are few factor columns.
53 pix2grid = function(from) {
54 n = .NumberOfCells(from@grid)
55 data = data.frame(matrix(nrow = n, ncol = ncol(from@data)))
56 data[[email protected],] = from@data # takes care of character columns
57 names(data) = names(from@data)
58 # Which columns have factors
59 fids = which(sapply(from@data, is.factor))
60 if (length(fids) > 0) {
61 for (fi in fids) {
62 v = vector(mode(from@data[[fi]]), n)
63 v = factor(rep(NA, n), levels = levels(from@data[[fi]]))
64 v[[email protected]] = from@data[[fi]]
65 data[,fi] = v
66 }
67 }
68 SpatialGridDataFrame(from@grid, data,
69 rebuild_CRS(slot(from, "proj4string")))
70 }
71 setAs("SpatialPixelsDataFrame", "SpatialGridDataFrame", pix2grid)
72
73 as.SGDF.SPixDF = function(from) {
74 # find rows with only NA's in attribute table:
75 sel = apply(sapply(from@data, is.na), 1, function(x) !all(x))
76 #sel = TRUE
77 if (!any(sel)) {
78 warning("complete map seems to be NA's -- no selection was made")
79 sel = rep(TRUE, length(sel))
80 }
81 #SpatialPixelsDataFrame(points = coordinates(from)[sel,],
82 # data = from@data[sel,,drop=FALSE], proj4string = CRS(proj4string(from)))
83 new("SpatialPixelsDataFrame",
84 new("SpatialPixels",
85 new("SpatialPoints", coords = coordinates(from)[sel,,drop=FALSE],
86 bbox = from@bbox, proj4string = from@proj4string),
87 grid = from@grid,
88 grid.index = which(sel)),
89 data = from@data[sel,,drop=FALSE])
90 }
91 setAs("SpatialGridDataFrame", "SpatialPixelsDataFrame", as.SGDF.SPixDF)
92 setAs("SpatialGridDataFrame", "SpatialPointsDataFrame",
93 function(from) as(as(from, "SpatialPixelsDataFrame"), "SpatialPointsDataFrame"))
94
95 setMethod("coordinates", "SpatialPixelsDataFrame",
96 function(obj) coordinates(as(obj, "SpatialPixels")))
97
98 setMethod("coordinates", "SpatialGridDataFrame",
99 function(obj) coordinates(as(obj, "SpatialGrid")))
100
101 row.names.SpatialGridDataFrame <- function(x) {
102 #warning("row.names order might be wrong!")
103 #1:prod(x@[email protected])
104 row.names(x@data)
105 }
106
107 as.SpPixDF.SpPoiDF = function(from)
108 new("SpatialPointsDataFrame", as(from, "SpatialPoints"),
109 data = from@data, coords.nrs = [email protected])
110 setAs("SpatialPixelsDataFrame", "SpatialPointsDataFrame", as.SpPixDF.SpPoiDF)
111
112 as.SpatialPolygonsDataFrame.SpatialPixelsDataFrame = function(from) {
113 df <- from@data
114 SP <- as(from, "SpatialPolygons")
115 row.names(df) <- row.names(SP)
116 SpatialPolygonsDataFrame(SP, df)
117 }
118
119 setAs("SpatialPixelsDataFrame", "SpatialPolygonsDataFrame",
120 as.SpatialPolygonsDataFrame.SpatialPixelsDataFrame)
121
122 as.matrix.SpatialPixelsDataFrame = function(x, ...) {
123 # fullgrid(x) = TRUE
124 x = as(x, "SpatialGridDataFrame")
125 as.matrix(x, ...)
126 }
127
128 as.array.SpatialGridDataFrame = function(x,...) {
129 d = gridparameters(x)$cells.dim
130 if (ncol(x@data) > 1)
131 d = c(d, ncol(x@data))
132 array(do.call(c, x@data), dim = d)
133 }
134 setAs("SpatialGridDataFrame", "array", function(from)
135 as.array.SpatialGridDataFrame(from))
136
137 setAs("SpatialPixelsDataFrame", "array", function(from)
138 as(as(from, "SpatialGridDataFrame"), "array"))
139
140 as.matrix.SpatialGridDataFrame = function(x, ..., byrow = FALSE) {
141 if (ncol(x@data) > 1)
142 warning(
143 "as.matrix.SpatialGridDataFrame uses first column;\n use subset or [] for other columns")
144 if (byrow)
145 matrix(x@data[[1]], x@[email protected][2], x@[email protected][1], byrow=byrow)
146 else
147 matrix(x@data[[1]], x@[email protected][1], x@[email protected][2], byrow=byrow)
148 }
149
150 setAs("SpatialPixelsDataFrame", "matrix", function(from)
151 as.matrix.SpatialPixelsDataFrame(from))
152 setAs("SpatialGridDataFrame", "matrix", function(from)
153 as.matrix.SpatialGridDataFrame(from))
154
155 as.data.frame.SpatialPixelsDataFrame = function(x, row.names, optional, ...)
156 as.data.frame(as(x, "SpatialPointsDataFrame"))
157
158 as.data.frame.SpatialGridDataFrame = function(x, row.names, optional, ...)
159 as.data.frame(as(x, "SpatialPixelsDataFrame"))
160
161 setAs("SpatialPixelsDataFrame", "data.frame", function(from)
162 as.data.frame.SpatialPixelsDataFrame(from))
163 setAs("SpatialGridDataFrame", "data.frame", function(from)
164 as.data.frame.SpatialGridDataFrame(from))
165
166 setMethod("[", "SpatialPixelsDataFrame", function(x, i, j, ... , drop = FALSE) {
167 grid = x@grid
168 x = as(x, "SpatialPointsDataFrame")
169 missing.i = missing(i)
170 missing.j = missing(j)
171 nargs = nargs() # e.g., a[3,] gives 2 for nargs, a[3] gives 1.
172 if (missing.i && missing.j) {
173 i = TRUE
174 j = TRUE
175 } else if (missing.j && !missing.i) {
176 if (nargs == 2) {
177 j = i
178 i = TRUE
179 } else {
180 j = TRUE
181 }
182 } else if (missing.i && !missing.j)
183 i = TRUE
184 if (is.matrix(i))
185 stop("matrix argument not supported in SpatialPointsDataFrame selection")
186 if (is(i, "Spatial"))
187 i = !is.na(over(x, geometry(i)))
188 if (any(is.na(i)))
189 stop("NAs not permitted in row index")
190 x@coords = x@coords[i, , drop = FALSE]
191 if (nrow(x@coords))
192 x@bbox = .bboxCoords(x@coords)
193 x@data = x@data[i, j, ..., drop = FALSE]
194 if (drop)
195 gridded(x) = TRUE
196 else
197 gridded(x) = list(TRUE, grid)
198 x
199 })
200 #setMethod("[", "SpatialPixelsDataFrame", subs.SpatialPixelsDataFrame)
201
202 subs.SpatialGridDataFrame <- function(x, i, j, ... , drop = FALSE) {
203 n.args = nargs()
204 dots = list(...)
205 if (drop)
206 stop("argument drop needs to be FALSE")
207 missing.i = missing(i)
208 missing.j = missing(j)
209 if (length(dots) > 0) {
210 missing.k = FALSE
211 k = dots[[1]]
212 } else
213 missing.k = TRUE
214 if (missing.i && missing.j && missing.k)
215 return(x)
216 grd = x@grid
217
218 if (missing.k) {
219 k = TRUE
220 if (missing.j && n.args != 3) { # not like : x[i,] but x[i]
221 x@data = x@data[ , i, drop = FALSE]
222 return(x)
223 }
224 } else if (missing.j && n.args == 2) {
225 x@data = x@data[ , k, drop = FALSE]
226 return(x)
227 }
228 if (missing.i)
229 rows = 1:[email protected][2]
230 else { # we have an i
231 if (is(i, "Spatial"))
232 i = !is.na(over(x, geometry(i)))
233 if (is.integer(i)) {
234 if ((length(i) > [email protected][2] && length(i) < nrow(x@data))
235 || max(i) > [email protected][2]) {
236 if (all(i < 0)) {
237 i = -i
238 negate = TRUE
239 } else
240 negate = FALSE
241 i = (1:nrow(x@data)) %in% i
242 if (negate)
243 i = !i
244 }
245 }
246 if (length(i) == nrow(x@data)) {
247 if (!missing.j)
248 x@data = x@data[j]
249 x@data = data.frame(lapply(x@data, function(C) { C[!i] = NA; C }))
250 return(x)
251 }
252 rows = i
253 }
254 if (missing.j)
255 cols = 1:[email protected][1]
256 else
257 cols = j
258 idx = 1:prod([email protected][1:2])
259 m = matrix(idx, [email protected][2], [email protected][1], byrow = TRUE)[rows,cols]
260 idx = as.vector(m) # t(m)?
261 if (any(is.na(idx)))
262 stop("NAs not permitted in index")
263 if (length(idx) == 0) {
264 x@data = x@data[,k,drop=FALSE]
265 x@data[] = NA
266 return(x)
267 }
268 pts = SpatialPoints(coordinates(x)[idx,,drop=FALSE],
269 rebuild_CRS(slot(x, "proj4string")))
270 if (length(idx) == 1)
271 SpatialPointsDataFrame(pts, x@data[idx, k, drop = FALSE])
272 else {
273 res = SpatialPixelsDataFrame(SpatialPixels(pts), x@data[idx, k, drop = FALSE])
274 as(res, "SpatialGridDataFrame")
275 }
276 }
277 setMethod("[", "SpatialGridDataFrame", subs.SpatialGridDataFrame)
278
279 cbind.SpatialGridDataFrame = function(...) {
280 stop.ifnot.equal = function(a, b) {
281 res = all.equal(getGridTopology(a), getGridTopology(b))
282 if (!is.logical(res) || !res)
283 stop("topology is not equal")
284 }
285 grds = list(...)
286 ngrds = length(grds)
287 if (ngrds < 1)
288 stop("no arguments supplied")
289 if (ngrds == 1)
290 return(grds[[1]])
291 # verify matching topology:
292 sapply(grds[2:ngrds], function(x) stop.ifnot.equal(x, grds[[1]]))
293 gr = grds[[1]]
294 gr@data = do.call(cbind, lapply(grds, function(x) x@data))
295 #for (i in 2:ngrds)
296 # gr@data = cbind(gr@data, grds[[i]]@data)
297 proj4string(gr) = rebuild_CRS(slot(grds[[1]], "proj4string"))
298 gr
299 }
300
301 print.SpatialPixelsDataFrame = function(x, ...) {
302 cat("Object of class SpatialPixelsDataFrame\n")
303 print(as(x, "SpatialPixels"))
304 if (length(x) > 0) {
305 cat("\n")
306 cat("Data summary:\n")
307 if (ncol(x@data) > 0)
308 print(summary(x@data))
309 }
310 invisible(x)
311 }
312 setMethod("show", "SpatialPixelsDataFrame",
313 function(object) print.SpatialPixelsDataFrame(object))
314
315 print.SpatialGridDataFrame = function(x, ...) {
316 cat("Object of class SpatialGridDataFrame\n")
317 print(as(x, "SpatialGrid"))
318 if (length(x) > 0) {
319 cat("\n")
320 cat("Data summary:\n")
321 if (ncol(x@data) > 1)
322 sobj = summary(x@data)
323 else sobj = summary(x@data[[1]])
324 print(sobj)
325 }
326 invisible(x)
327 }
328 setMethod("show", "SpatialGridDataFrame",
329 function(object) print.SpatialGridDataFrame(object))
330
331 names.SpatialPixelsDataFrame = function(x) names(x@data)
332 names.SpatialGridDataFrame = function(x) names(x@data)
333
334 checkNames = function(x) {
335 if (!identical(x, make.names(x)))
336 warning("attempt to set invalid names: this may lead to problems later on. See ?make.names")
337 }
338 "names<-.SpatialPixelsDataFrame" = function(x,value) { checkNames(value); names(x@data) = value; x }
339 "names<-.SpatialGridDataFrame" = function(x,value) { checkNames(value); names(x@data) = value; x }
340
341 dim.SpatialPixelsDataFrame = function(x) dim(x@data)
342
343
344 dim.SpatialGridDataFrame = function(x) dim(x@data)
345
346 setMethod("split", "SpatialPixelsDataFrame", split.data.frame)
347
348 setMethod("geometry", "SpatialGridDataFrame",
349 function(obj) as(obj, "SpatialGrid"))
350
351 setMethod("geometry", "SpatialPixelsDataFrame",
352 function(obj) as(obj, "SpatialPixels"))
353
354 setAs("SpatialGridDataFrame", "SpatialPolygonsDataFrame",
355 function(from) {
356 fullgrid(from) = FALSE
357 as(from, "SpatialPolygonsDataFrame")
358 }
359 )
360
361 length.SpatialPixelsDataFrame = function(x) { nrow(x@coords) }
362 length.SpatialGridDataFrame = function(x) { .NumberOfCells(x@grid) }
363
364 # http://menugget.blogspot.de/2013/12/new-version-of-imagescale-function.html
365 #This function creates a color scale for use with the image()
366 #function. Input parameters should be consistent with those
367 #used in the corresponding image plot. The "axis.pos" argument
368 #defines the side of the axis. The "add.axis" argument defines
369 #whether the axis is added (default: TRUE)or not (FALSE).
370 .image.scale <- function(z, zlim, col = heat.colors(12), breaks, axis.pos=1, add.axis = TRUE,
371 at = NULL, shrink = 0, ...) {
372 stopifnot(!is.factor(z))
373 if (!missing(breaks) && length(breaks) != (length(col) + 1))
374 stop("must have one more break than colour")
375 if (missing(zlim))
376 zlim <- range(z, na.rm=TRUE)
377 if (missing(breaks))
378 breaks <- seq(zlim[1], zlim[2], length.out = length(col) + 1)
379 Shrink = function(r, s) {
380 w = diff(r)
381 c(r[1] - 0.5 * s * w, r[2] + 0.5 * s * w)
382 }
383 if (axis.pos %in% c(1,3)) {
384 ylim <- c(0, 1)
385 xlim <- Shrink(range(breaks), shrink)
386 }
387 if (axis.pos %in% c(2,4)) {
388 ylim <- Shrink(range(breaks), shrink)
389 xlim <- c(0, 1)
390 }
391 poly <- vector(mode="list", length(col))
392 for (i in seq(poly))
393 poly[[i]] <- c(breaks[i], breaks[i+1], breaks[i+1], breaks[i])
394 plot(1,1,t="n", ylim = ylim, xlim = xlim, axes = FALSE,
395 xlab = "", ylab = "", xaxs = "i", yaxs = "i", ...)
396 for(i in seq(poly)) {
397 if (axis.pos %in% c(1,3))
398 polygon(poly[[i]], c(0,0,1,1), col=col[i], border=NA)
399 if (axis.pos %in% c(2,4))
400 polygon(c(0,0,1,1), poly[[i]], col=col[i], border=NA)
401 }
402 if (shrink > 0) {
403 if (is.null(at))
404 at = pretty(breaks)
405 b = c(breaks[1], breaks[length(breaks)])
406 if (axis.pos %in% c(1,3))
407 lines(y = c(0,1,1,0,0), x = c(b[1],b[1],b[2],b[2],b[1]))
408 if (axis.pos %in% c(2,4))
409 lines(x = c(0,1,1,0,0), y = c(b[1],b[1],b[2],b[2],b[1]))
410 } else
411 box()
412 if (add.axis)
413 axis(axis.pos, at)
414 }
415
416 .image.scale.factor <- function(z, col = heat.colors(nlevels(z)), axis.pos = 1, scale.frac = 0.3,
417 scale.n = 15, ...) {
418 stopifnot(is.factor(z))
419 stopifnot(axis.pos %in% c(1,4))
420 frc = scale.frac
421 stre = scale.n
422 plot(1, 1, t="n", ylim = c(0,1), xlim = c(0,1), axes = FALSE,
423 xlab = "", ylab = "", xaxs = "i", yaxs = "i", ...)
424 n = nlevels(z)
425 if (n != length(col))
426 stop("# of colors must be equal to # of factor levels")
427 lb = (1:n - 0.5)/max(n, stre) # place of the labels
428 poly <- vector(mode="list", length(col))
429 breaks = (0:n) / max(n, stre)
430 if (n < stre) { # center
431 breaks = breaks + (stre - n)/(2 * stre)
432 lb = lb + (stre - n)/(2 * stre)
433 }
434 for (i in seq(poly))
435 poly[[i]] <- c(breaks[i], breaks[i+1], breaks[i+1], breaks[i])
436 for(i in seq(poly)) {
437 if (axis.pos %in% c(1,3))
438 polygon(poly[[i]], c(1,1,1-frc,1-frc), col=col[i], border=NA)
439 if (axis.pos %in% c(2,4))
440 polygon(c(0,0,frc,frc), poly[[i]], col=col[i], border=NA)
441 }
442 b = c(breaks[1], breaks[length(breaks)])
443 if (axis.pos %in% c(1,3)) {
444 lines(y = c(1,1-frc,1-frc,1,1), x = c(b[1],b[1],b[2],b[2],b[1]))
445 # text(x = 1.05 * frc, y = lb, levels(z), pos = axis.pos)
446 text(y = (1-frc)/1.05, x = lb, levels(z), pos = axis.pos)
447 }
448 if (axis.pos %in% c(2,4)) {
449 lines(x = c(0,frc,frc,0,0), y = c(b[1],b[1],b[2],b[2],b[1]))
450 text(x = 1.05 * frc, y = lb, levels(z), pos = axis.pos)
451 }
452 }
453
454 plot.SpatialGridDataFrame = function(x, ..., attr = 1, col, breaks,
455 zlim = range(as.numeric(x[[attr]])[is.finite(x[[attr]])]),
456 axes = FALSE, xaxs = "i", yaxs = xaxs, at = NULL,
457 border = NA, axis.pos = 4, add.axis = TRUE, what = "both", scale.size = lcm(2.8),
458 scale.shrink = 0, scale.frac = 0.3, scale.n = 15) {
459
460 if (missing(col)) {
461 if (is.factor(x[[1]]))
462 col = RColorBrewer::brewer.pal(nlevels(x[[1]]), "Set2")
463 else
464 col = bpy.colors(100) # heat.colors(12)
465 }
466 image.args = list(x = x, col = col, zlim = zlim, axes = axes, xaxs = xaxs, yaxs = yaxs, ...)
467 if (all(c("red", "green", "blue") %in% names(image.args))) # legend off:
468 what = "image"
469 else # plot band 1:
470 image.args$x = x[1]
471 if (!missing(breaks))
472 image.args$breaks = breaks
473 si = scale.size
474 if (what == "both")
475 switch (axis.pos,
476 layout(matrix(c(2,1), nrow=2, ncol=1), widths=1, heights=c(1,si)), # 1
477 layout(matrix(c(1,2), nrow=1, ncol=2), widths=c(si,1), heights=1), # 2
478 layout(matrix(c(1,2), nrow=2, ncol=1), widths=1, heights=c(si,1)), # 3
479 layout(matrix(c(2,1), nrow=1, ncol=2), widths=c(1,si), heights=1) # 4
480 )
481 # scale:
482 if (what %in% c("both", "scale")) {
483 mar = c(1,1,1,1)
484 if (! is.factor(x[[1]]))
485 mar[axis.pos] = 3
486 if (axes && axis.pos %in% c(2,4))
487 mar[1] = 3
488 if (axes && axis.pos %in% c(1,3))
489 mar[2] = 3
490 par(mar = mar)
491 if (is.factor(x[[1]]))
492 .image.scale.factor(x[[1]], col = col, axis.pos = axis.pos, scale.frac = scale.frac,
493 scale.n = scale.n)
494 else
495 .image.scale(x[[1]], zlim = zlim, col = col, breaks = breaks, axis.pos = axis.pos,
496 add.axis = add.axis, at = at, shrink = scale.shrink)
497 # axis(axis.pos)
498 }
499 if (what %in% c("both", "image")) {
500 if (is.factor(x[[1]]))
501 image.args$x[[1]] = as.numeric(x[[1]])
502 mar=c(1,1,1,1)
503 if (axes)
504 mar[1:2] = 3
505 par(mar = mar)
506 do.call(image, image.args)
507 if (!is.na(border))
508 plot(geometry(x), col = border, add = TRUE)
509 }
510 }
511
512 setMethod("plot", signature(x = "SpatialGridDataFrame", y = "missing"),
513 function(x,y,...) plot.SpatialGridDataFrame(x,...))
514
515 setMethod("plot", signature(x = "SpatialPixelsDataFrame", y = "missing"),
516 function(x,y,...) plot.SpatialGridDataFrame(x,...))