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?
-
1Erp, no it looks like a use-case the author of spdplyr did not test. :[mdsumner– mdsumner2017年01月27日 13:50:37 +00:00Commented 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.eivindhammers– eivindhammers2017年01月27日 14:02:02 +00:00Commented Jan 27, 2017 at 14:02
-
No problem, feel free to do that in future.mdsumner– mdsumner2017年01月27日 14:04:27 +00:00Commented Jan 27, 2017 at 14:04
1 Answer 1
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 tosp
from time to time, since I can't always findsf
functions to fulfill all the needs of my workflow (or there are too many lines of code to do whatsp
-packages can do with one line).eivindhammers– eivindhammers2017年01月27日 14:12:52 +00:00Commented 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 withas(x_sf, "Spatial")
andst_as_sf(x_Spatial)
. Also worth asking on the Github sites (edzer/sfr) and (r-spatial/discuss) for general queries.mdsumner– mdsumner2017年01月29日 02:25:53 +00:00Commented Jan 29, 2017 at 2:25