I have a shapefile of multipolygons and I want to find the centroid of each multipolygon, but instead I am getting the centroid of the whole shapefile.
I converted my csv file into a shapefile (see this question Converting CSV file to shapefile - but want polygon not points) using the following lines of code:
df <- as.data.frame(read_csv("/Users/alan/Desktop/shapes.csv"))
df1 <- lapply(split(df, df$shape), function(x) { coords <- as.matrix(cbind(x$longitude,
x$latitude)); rbind(coords, coords[1,])})
Coord_Ref <- st_crs(3035)
plot_locations_df <- st_multipolygon(x=list(df1))
plot_locations_df <- st_sfc(plot_locations_df, crs = Coord_Ref)
plot(st_geometry(plot_locations_df))
plot(st_geometry(plot_locations_df, col = sf.colors(12, categorical=TRUE), border='grey',
axes=TRUE))
plot(st_geometry(st_centroid(plot_locations_df)), pch = 3, col = 'red', add=TRUE)
My dataframe looks like this:
structure(list(shape = c(1.1, 1.1, 1.1, 1.1, 2.1, 2.1, 2.1, 2.1,
3.1, 3.1, 3.1, 3.1, 4.1, 4.1, 4.1, 4.1, 5.1, 5.1, 5.1, 5.1, 6.1,
6.1, 6.1, 6.1, 7.1, 7.1, 7.1, 7.1, 8.1, 8.1, 8.1, 8.1, 9.1, 9.1,
9.1, 9.1), longitude = c(43, 43, 40, 40, 23, 23, 20, 20, 25,
25, 38, 38, 25, 25, 38, 38, 45, 50, 50, 45, 65, 60, 60, 65, 60,
60, 80, 80, 60, 60, 80, 80, 20, 20, 80, 80), latitude = c(10,
13, 13, 10, 10, 13, 13, 10, 10, 10.3, 10.3, 10, 12.7, 13, 13,
12.7, 13, 13, 10, 10, 13, 13, 10, 10, 9.8, 9.5, 9.5, 9.8, 6,
5.7, 5.7, 6, 5, 4.5, 4.5, 5)), row.names = c(NA, 36L), class = "data.frame")