Skip to content

Instantly share code, notes, and snippets.

@dholstius
Last active March 22, 2016 12:46
Show Gist options
  • Save dholstius/58818dc9bbb88968ec0b to your computer and use it in GitHub Desktop.
Save dholstius/58818dc9bbb88968ec0b to your computer and use it in GitHub Desktop.
filter_() methods for Spatial*DataFrame objects
#' Filter (subset) a Spatial*DataFrame object
#'
#' @param object a \code{Spatial*DataFrame}
#' @param ... see \link{subset}
#' @param .dots
#'
#' @importFrom lazyeval all_dots lazy_eval
#'
#' @return a subset of the original \code{Spatial*DataFrame}
#'
#' @seealso subset
#'
#' @examples
#' library(dplyr)
#' library(sp)
#' data(meuse, package = "sp")
#' j <- which(names(meuse) %in% c("x", "y"))
#' meuse_spdf <- SpatialPointsDataFrame(meuse[, j], meuse[, -j])
#' high_copper <- filter(meuse_spdf, copper > median(copper))
#' stopifnot(inherits(high_copper, class(meuse_spdf)))
#'
#' @export
filter_.SpatialDataFrame <- function (object, ..., .dots) {
dots <- lazyeval::all_dots(.dots, ..., all_named = TRUE)
masks <- lazyeval::lazy_eval(dots, data = as.data.frame(object@data))
subset(object, Reduce(`&`, masks))
}
# FIXME: @describeIn makes roxygen complain "Don't know how to describe s3method in s3method"
# @describeIn filter_.SpatialDataFrame
filter_.SpatialLinesDataFrame <- filter_.SpatialDataFrame
# @describeIn filter_.SpatialDataFrame
filter_.SpatialPointsDataFrame <- filter_.SpatialDataFrame
# @describeIn filter_.SpatialDataFrame
filter_.SpatialPolygonsDataFrame <- filter_.SpatialDataFrame
@mdsumner
Copy link

I've done mutate, transmute, select, slice, rename, arrange and distinct. Shall we create a simple package for just these methods? Here's what I have: https://gist.github.com/mdsumner/85d76f8b33e26a427c3d Originally I was seeing this through a different lens of flattening to a table - but that might be a good way to handle joins.

I think summarise is best left undefined for now.

There's probably a bunch of things I'm not doing properly here, so happy for any feedback / discussion.

@mdsumner
Copy link

And here's my packaging of it: https://github.com/mdsumner/spbabel

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment