2

I'm trying to drop columns/attributes from a SpatialPointsDataFrame, using spdplyr, like so:

library(sp)
library(spdplyr)

x <- c(15.2, 15.3, 15.4, 15.5, 15.7)
y <- c(50.4, 50.2, 50.3, 50.1, 50.4)
v1 <- c(1.0, 2.0, 3.0, 4.0, 5.0)
v2 <- c("a","b","b","c","a")
attributes <- as.data.frame(cbind(v1,v2))
xy <- cbind(x,y)
locationsDD <- SpatialPointsDataFrame(xy, attributes)

locationsDD <- select(locationsDD, -v2)

With the result

Error in `[.data.frame`(x@data, i, j, ..., drop = FALSE) : 
  undefined columns selected

With SpatialPolygonsDataFrames this method works without issues. Is this a bug, or am I doing something wrong?

  • 1
    Erp, no it looks like a use-case the author of spdplyr did not test. :[ – mdsumner Jan 27 '17 at 13:50
  • Thanks. I see you have commited a fix. I realize my question may have been better suited as a GitHub issue. – eivindhammers Jan 27 '17 at 14:02
  • No problem, feel free to do that in future. – mdsumner Jan 27 '17 at 14:04
3

The problem is that the internal method doesn't apply drop = FALSE in the subset.

You can install from Github if you want the fix:

devtools::install_github("mdsumner/spdplyr")

But, I recommend moving to sf it's much better all round, and no need for spdplyr any more. Here's the code I would use (I've decided not to have auto-factor-creation):

library(sf)
locationsDD <- st_as_sf(data.frame(x = c(15.2, 15.3, 15.4, 15.5, 15.7), y = c(50.4, 50.2, 50.3, 50.1, 50.4), 
  v1 = c(1.0, 2.0, 3.0, 4.0, 5.0), v2 = c("a","b","b","c","a"), stringsAsFactors = FALSE), 
  coords = c("x", "y"))

library(dplyr)
select(locationsDD, -v2)
  • Thanks. I am in the process of migrating to sf, but I find myself switching back to sp from time to time, since I can't always find sf functions to fulfill all the needs of my workflow (or there are too many lines of code to do what sp-packages can do with one line). – eivindhammers Jan 27 '17 at 14:12
  • True enough, but it's still probably better (probably...) to use sf upfront and only go to Spatial when you need to, the round-trip is easy with as(x_sf, "Spatial") and st_as_sf(x_Spatial). Also worth asking on the Github sites (edzer/sfr) and (r-spatial/discuss) for general queries. – mdsumner Jan 29 '17 at 2:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.