I have a table of all Stop and Frisks that happened in 2017. I am given coordinates of where they happened in Long Island coordinates, but I want to convert it to latitude and longitude coordinates so that I can plot it in Leaflet.
I have the following snippet of code:
library(sp)
library(dplyr)
fd <- "https://www1.nyc.gov/assets/nypd/downloads/excel/analysis_and_planning/stop-question-frisk/sqf-2017.csv"
stop_and_frisk <- read.csv(fd)
saf <- stop_and_frisk %>% filter(STOP_FRISK_ID < 5 ) # filtering to keep data small
saf_spdf <- saf
coordinates(saf_spdf) <- ~STOP_LOCATION_X + STOP_LOCATION_Y
CRS_obj <- CRS('+proj=lcc +lat_1=41.03333333333333 +lat_2=40.66666666666666 +lat_0=40.16666666666666 +lon_0=-74 +x_0=300000.0000000001 +y_0=0 +ellps=GRS80 +datum=NAD83 +to_meter=0.3048006096012192 +no_defs')
spTransform(saf_spdf, CRS_obj)
I would expect that the coordinates would transform but instead I keep getting the error message
No transformation possible from NA reference system
And I'm not sure why. I haven't done very many CRS transformations before. I think the code above should sufficiently recreate the problem
The proj4string
(same as CRS) isn't set, which explains the error: spTransform(): “No transformation possible from NA reference system”
.
If you inspect the proj4string
, you'll see that it is NA
.
coordinates(saf_spdf) <- ~STOP_LOCATION_X + STOP_LOCATION_Y
proj4string(saf_spdf)
Retuns:
[1] NA
You need to first SET the proj4string
of this object, and then you can transform it to the lat/lon that leaflet()
takes.
# make data.frame a spatial object
coordinates(saf_spdf) <- ~STOP_LOCATION_X + STOP_LOCATION_Y
# SET the CRS of the object
proj4string(saf_spdf) <- CRS('the CRS of these coordinates as a character string')
# NOW we can transform to lat/lon
new <- spTransform(saf_spdf, CRS("+proj=longlat +ellps=WGS84 +datum=WGS84"))
# and finally, leaflet will accept this spatial object
new %>% leaflet()
Some intuition behind this error:
Spatial transforms work like this: (1) R needs to know what reference system you're in to begin with; (2) once we know what the starting reference system is, then and only then can we transform those points into a new reference system. You're getting this error because you haven't specified WHERE to begin. You can't transform something if you don't know where it's starting from. This like asking a computer to "multiply by 5". We need something to "multiply" in the first place! Setting a CRS tells R where to start the transformation.