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?

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

1 Answer 1

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)
answered Jan 27, 2017 at 14:06
2
  • 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). Commented Jan 27, 2017 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. Commented Jan 29, 2017 at 2:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.