0

I'm trying to find the center of Montana using the R centroid function in the geosphere package. The lat/long coordinates are stored in a shape file stored in xx that when calculated yield a result near Bermuda.

Any suggestions as to how to fix this?

geosphere::centroid(as.matrix(xx))
#           lon      lat
#[1,] -62.60957 28.57984
range(xx$long)
#-116.0492 -104.0391
range(xx$lat)
#44.38032 49.00091

Here's xx: https://pastebin.com/uFgmph9g

For reference enter image description here

Rafael
  • 3,096
  • 1
  • 23
  • 61

1 Answers1

0

I think you can calculate the coordinate of the centroid by averaging the coordinate of all the points, as this link suggested (https://gis.stackexchange.com/questions/6025/find-the-centroid-of-a-cluster-of-points).

cen <- colMeans(xx)
cen
#       long        lat 
# -110.27848   46.91494 

Here is a visualization to see if the centroid calculation makes sense. Red dot is the centroid.

library(sf)
library(leaflet)
library(mapview)

xx2 <- st_as_sf(xx, coords = c("long", "lat"), crs = 4326)
cen2 <- st_as_sf(as.data.frame(t(cen)), coords = c("long", "lat"), crs = 4326)

mapview(xx2) + mapview(cen2, col.regions = "red")

enter image description here

www
  • 38,575
  • 12
  • 48
  • 84
  • Thanks, `colMeans` works well for MT in this case since its a nice rectangle, but `centroids` is much better for less regular shapes. Except in this case, it's giving me a very strange result. – Rafael Feb 01 '18 at 12:26
  • What is the definition of centroid? I thought the centroid is the mean of the coordinates. – www Feb 01 '18 at 12:34
  • I assume the shape of point distribution would not affect the definition of centroid. – www Feb 01 '18 at 12:36
  • 1
    The centroid function from the geosphere package works for polygon. Your example is a point pattern, so it is probably not suitable in this case. – www Feb 01 '18 at 12:38
  • `?centroid` says it takes class `matrix` as `x`.. Wouldn't a matrix always be a point pattern? – Rafael Feb 01 '18 at 13:10
  • The first sentence of the documentation says “Compute the centroid of longitude/latitude polygons.” I believe the function would work if your matrix contains the points defining a polygon. However, the example dataset you provided does not look like a polygon. – www Feb 01 '18 at 13:37
  • 1
    Also, as you're using `library(sf)`, it also has a `st_centroid()` function. – SymbolixAU Feb 06 '18 at 23:29