I'm trying to intersect two sf objects for the US (one at the township level and the other one at the census tract level). I'm getting both using tigris
and tidycensys
. My final goal is to have an unique sf object with information at the township level (with information from both the originals township and census tract level sf objects). And after I do this intersection, I want to export this sf object using st_write
from the sf
package. Here is the code I've used:
library(tigris)
library(sf)
library(purrr)
library(tidycensus)
library(tidyr)
library(dplyr)
##Data at township level
#---------------------------#
MN_Township_SHP <- county_subdivisions("Minnesota", cb = TRUE)%>% st_transform(., crs=32618)
MN_Township_SHP$County <- substr(MN_Township_SHP$NAMELSADCO,1,nchar(MN_Township_SHP$NAMELSADCO)-7)
Dataset <- MN_Township_SHP
#Data at census tract level
#---------------------------#
Sys.getenv("CENSUS_API_KEY")
my_vars <-
c(total_pop = "B01003_001",
race_denominator = "B02001_001", #Total
white = "B02001_002")
mn <- unique(fips_codes$state)[24]
MN_CensusTract_SHP <-map_df(mn, function(x) {
get_acs(geography = "tract",
geometry = T,
variables = my_vars,
state = mn) })
MN_CensusTract_SHP <- MN_CensusTract_SHP %>% dplyr::select(-moe)
Social_Dat <-
MN_CensusTract_SHP %>%
as.data.frame() %>%
pivot_wider(names_from = variable,
values_from = c(estimate)) %>%
dplyr::mutate(year=2021) %>%
dplyr::rename_all(funs(paste0("ACS_", .)))
Social_Dat$ACS_year <- as.double(Social_Dat$ACS_year)
Social_Dat$ACS_GEOID <- as.double(Social_Dat$ACS_GEOID)
Social_Dat <- st_as_sf(Social_Dat, sf_column_name = 'ACS_geometry')%>% st_transform(., crs=32618)
#Intersection between township and census tract levels
#---------------------------#
final_df <- st_intersection(Dataset, Social_Dat, all=TRUE)
#Export sf object as shapefile
#---------------------------#
st_write(final_df, "Input_Intermediate/final_df.shp", delete_layer = TRUE)
However, when I run this final step, I get the following error:
"Error in CPL_write_ogr(obj, dsn, layer, driver, as.character(dataset_options), : Write error"
Does anyone know how to solve this? I've tried so many ways that I found in google, but none of them worked for me. Many thanks in advance!!!
I was able to solve this issue by doing the following: