library(tidycensus)
library(tidyverse)
library(sf)
Define variables for the Census variable that defines median monthly housing costs, geography (several counties in Texas), and the output shapefile name. Finally, use the get_acs() function to extract 2012 and 2017 data frames.
var = "B25105_001" ## Median Monthly Housing Costs
st = 'TX'
counties = c("Travis", "Williamson", "Hays", "Bastrop", "Caldwell")
shp = "AustinMetroTracts_Median_Monthly_Housing_Costs.shp"
df2017 = get_acs(geography = "tract", variables = var, state=st, county=counties, geometry = TRUE, year = 2017, cache_table = TRUE)
df2012 = get_acs(geography = "tract", variables = var, state=st, county=counties, geometry = FALSE, year = 2012, cache_table = TRUE)
Use the reduce() function to join the 2012 and 2017 data frames. The select() function is used to rename the columns. The mutate() function creates a new CHANGE column containing the percent change in median monthly housing costs from 2012 to 2017.
lstYrs = list(df2017, df2012)
dfJoin = reduce(lstYrs, left_join, by = c("GEOID"))
dfJoin = select(dfJoin, GEOID, NAME = NAME.x, `YR_2017` = estimate.x, `YR_2012` = estimate.y)
dfJoin = mutate(dfJoin, CHANGE = ((YR_2017 - YR_2012) / YR_2012) * 100)
head(dfJoin)
## Simple feature collection with 6 features and 5 fields
## geometry type: MULTIPOLYGON
## dimension: XY
## bbox: xmin: -97.568 ymin: 29.95465 xmax: -97.04821 ymax: 30.41964
## epsg (SRID): 4269
## proj4string: +proj=longlat +datum=NAD83 +no_defs
## GEOID NAME YR_2017 YR_2012
## 1 48021950100 Census Tract 9501, Bastrop County, Texas 878 838
## 2 48021950200 Census Tract 9502, Bastrop County, Texas 950 855
## 3 48021950300 Census Tract 9503, Bastrop County, Texas 1055 1190
## 4 48021950400 Census Tract 9504, Bastrop County, Texas 1012 1034
## 5 48021950501 Census Tract 9505.01, Bastrop County, Texas 879 856
## 6 48021950502 Census Tract 9505.02, Bastrop County, Texas 873 1153
## CHANGE geometry
## 1 4.773270 MULTIPOLYGON (((-97.49111 3...
## 2 11.111111 MULTIPOLYGON (((-97.40984 3...
## 3 -11.344538 MULTIPOLYGON (((-97.568 30....
## 4 -2.127660 MULTIPOLYGON (((-97.35017 3...
## 5 2.686916 MULTIPOLYGON (((-97.37325 3...
## 6 -24.284475 MULTIPOLYGON (((-97.30356 3...
The st_write() function from the sf package can be used to write a data frame to a shapefile.
st_write(dfJoin, shp)
## Writing layer `AustinMetroTracts_Median_Monthly_Housing_Costs' to data source `AustinMetroTracts_Median_Monthly_Housing_Costs.shp' using driver `ESRI Shapefile'
## features: 350
## fields: 5
## geometry type: Multi Polygon