library(ipumsr)
ddi <- read_ipums_ddi("C:/Users/chrys/Documents/GitHub/DEM7093/data/usa_00004.xml")
data <- read_ipums_micro(ddi)
## Use of data from IPUMS USA is subject to conditions including that users should
## cite the data appropriately. Use command `ipums_conditions()` for more details.
data<-haven::zap_labels(data) #necessary to avoid problems with "labelled" data class
names(data)<-tolower(names(data))

Download geographic data for Public Use Microdata Areas

options(tigris_class = "sf")
pumas<-pumas(state = "CA",
             year = 2019,
             cb = T)

plot(pumas["GEOID10"],
     main = "Public Use Microdata Areas in California")

Prepare variables

Recoded 0=NA and 9=unknown as missing

data$pwt <- data$perwt
data$hwt <- data$hhwt
data$same <- Recode(data$migrate1, recodes = "1 = 1; 2:4 = 0; else = NA")

Generate survey design object

des<-svydesign(ids = ~cluster,
               strata = ~ strata,
               weights = ~pwt,
               data = data)

perform survey estimation for PUMAs

puma_est_same <- svyby(formula = ~same,
                    by = ~puma,
                    design = des,
                    FUN=svymean,
                    na.rm = TRUE )

puma_est_same$same_pct = round(puma_est_same$same*100,1)

join to geography

pumas$puma<-as.numeric(pumas$PUMACE10)

geo1<-left_join(pumas, puma_est_same, by=c("puma"= "puma"))

Map estimates

Percent lived in same house last year by PUMA

#can change tmap mode to "view" or "plot"
tmap_mode("plot")

geo1%>%
  tm_shape()+
  tm_polygons("same_pct",
              title = "Percent same house \n last year",
              palette = "Blues",
              style= "quantile",#"kmeans",
              n=6,
              legend.hist = TRUE) +
  tm_layout(legend.outside = TRUE,
            main.title = "Percent of population that lived in the same house in the last year by California PUMAs \n 2015-2019",
            title.position = c('center', 'top')) +
  tm_format("World",
            legend.position =  c("left", "top"),
            legend.title.size = 1,
            legend.text.size = .9,
            main.title.size = 1)