For the U.S., I can get the centroids of all the counties in a state. However, upon closer inspection, the centroid of some counties is not correct. How can I manually correct the point geometry (latitude and longitude) for a given county?
Example of Virginia
library(dplyr) # data wrangling
library(sf) # for getting centroids
library(tigris) # for getting county shapefile
library(cdlTools) # converting state fips to state name
library(ggplot2) # for mapping
### Extract centroids for each county in the USA
centroids <- counties(resolution = "20m") %>%
st_centroid()
centroids$STATE_NAME <- fips(centroids$STATEFP, to = 'Name')
va_cnty <- centroids[centroids$STATE_NAME %in% 'Virginia',]
### Make map of VA showing location of county centroids ----
state_shp <- states(cb = T)
state_shp$STATEFP <- as.numeric(state_shp$STATEFP)
state_shp <- state_shp[state_shp$STATEFP %in% c(1,3:14,16:56),]
cnty_shp <- counties(cb = TRUE)
cnty_shp$STATEFP <- as.numeric(cnty_shp$STATEFP)
lower48_shp <- cnty_shp[cnty_shp$STATEFP %in% c(1,3:14,16:56),]
va_shp <- lower48_shp[lower48_shp$STUSPS == 'VA',]
ggplot() +
geom_sf(data = state_shp,
mapping = aes(geometry = geometry),
color = 'black',
fill = 'gray70') +
geom_sf(data = va_shp,
mapping = aes(geometry = geometry),
color = 'black',
fill = 'lightyellow') +
geom_sf(data = va_cnty,
mapping = aes(geometry = geometry),
color = "black",
fill = 'red',
shape = 21,
size = 3) +
coord_sf(xlim = c(-83.5, -75), ylim = c(36.4, 39.5), expand = TRUE) +
theme_bw() +
theme(text = element_text(size = 16),
axis.text.x = element_text(size = 14, color = "black"),
axis.text.y = element_text(size = 14, color = "black"),
panel.grid.major = element_blank(),
panel.background = element_rect(fill = "lightblue"))
Map of the center lat and long of each county in Virginia
How can I change the latitude and longitude in the geometry column of va_cnty
? The correct latitude and longitude are: 37.772236, -75.660827
Two unsuccessful attempts
va_cnty[va_cnty$NAME %in% 'Accomack',7] <- st_point(c(-75.660827,37.772236))
# Error in `[<-.data.frame`(`*tmp*`, va_cnty$NAME %in% "Accomack", 7, value = c(-75.660827,: replacement has 2 rows, data has 1
sfc = st_sfc(st_point(c(-75.660827,37.772236)), crs = 'NAD83')
va_cnty[va_cnty$NAME %in% 'Accomack',7] <- sfc
# Warning message:
# In `[<-.data.frame`(`*tmp*`, va_cnty$NAME %in% "Accomack", 7, value = # list( : replacement element 1 has 2 rows to replace 1 rows