Reputation: 61
I have this, and I am trying to use gDistance
to calculate the distance between each centroid and the city of Baghdad. I am trying to do it like this:
gDistance(districts_centroids, districts@data$ADM3NAME %in% c("Baghdad"), byid=TRUE)
Where district_centroids
are Formal Class SpatialPoints
, and the districts@data...
is basically the city of Baghdad in the shp
file.
I get an error saying the following:
Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘is.projected’ for signature ‘"logical"’ In addition: Warning message: In RGEOSDistanceFunc(spgeom1, spgeom2, byid, "rgeos_distance") : Spatial object 1 is not projected; GEOS expects planar coordinates
I am completely new to R and I don't really know what's going on.
Any help would be appreciated
Thank you!
Upvotes: 2
Views: 1342
Reputation: 1388
This is a great question. After taking a look at things, it was decided the best way to answer this question was using simple feature objects
rather than spatial objects.
The map in question looks familiar. I used the IRQ_2_sf.rds
map which is probably the same map used and shown above. There are other alternative ways to achieve the solution to this question. Jupyter Lab is the IDE used.
Using the Google API and the geocode
function, the coordinates for Baghdad were retrieved.
baghdad <- geocode("Baghdad, Iraq", source = c("google") )
A tibble: 1 × 2
lon lat
<dbl> <dbl>
44.36607 33.31524
Then sf
functions were used to create the sf column object
.
baghdad.sfg <- st_point(c(lon, lat), dim = "XY")
baghdad.sfc <- st_sfc(baghdad.sfg, crs = 4326)
Then, using the sf map named iraq, the centroids
were created.
Note: warning message - st_centroid does not give correct centroids for longitude/latitude data. For this answer, the centroids will be close
enough.
iraq.c <- st_centroid(iraq)
The distance from each centroid
to Baghdad gets determined in kilometers.
head(dist <- data.frame(c(st_distance(iraq.c$geom[], baghdad.sfc)/1000)))
Units: [m]
[1] 28.63250 59.61553 215.43354 323.06418 259.14509 113.55356
And then create a date frame that includes the names, the centroid
geometry and the distance values. Requires some cleaning and binding.
distance <- c(dist$c.st_distance.iraq.c.geom....baghdad.sfc..1000.)
x <- distance[]
d_Bdad_Km <- as.numeric(str_extract(x, "[0-9]*.[0-9]."))
iraq2 <- iraq[-c(5, 8,9,10,11,12,13)]
df_dist <- cbind(iraq2, d_Bdad_Km) # df as desired
And then the outputs gets plotted
.
plot(iraq$geom)
plot(iraq.c$geom, add = TRUE, col = "red")
plot(baghdad.sfc, add = TRUE, pch = 19, col = "blue")
Please ask if there are any follow-up questions. The plot can be viewed at this link:
Upvotes: 2