-
Notifications
You must be signed in to change notification settings - Fork 449
/
cog.Rmd
380 lines (274 loc) · 11.4 KB
/
cog.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# Census of Governments (COG) {-}
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) <a href="https://github.com/asdfree/cog/actions"><img src="https://github.com/asdfree/cog/actions/workflows/r.yml/badge.svg" alt="Github Actions Badge"></a>
Location, employment, and payroll for state and local (but not federal) government agencies in the U.S.
* One record per agency, one per agency function, plus the government units master address file.
* Complete enumeration of civilian employment in state and local governments in the 50 states + D.C.
* The Annual Survey of Public Employment & Payroll becomes a census in years ending with 2 and 7.
* Administered and financed by the [US Census Bureau](http://www.census.gov/).
---
## Recommended Reading {-}
Two Methodology Documents:
> [2022 Census of Governments, Survey of Public Employment & Payroll Methodology](https://www2.census.gov/programs-surveys/apes/technical-documentation/methodology/22_methodology.pdf)
> [Government Units Survey Methodology](https://www.census.gov/programs-surveys/gus/technical-documentation/methodology.html)
<br>
One Haiku:
```{r}
# courthouse steps wedding
# schools police fire water
# no fed mail invite
```
---
## Download, Import, Preparation {-}
Download, import, and stack the government units listing file:
```{r eval = FALSE , results = "hide" }
library(readxl)
tf_gus <- tempfile()
gus_url <- "https://www2.census.gov/programs-surveys/gus/datasets/2022/govt_units_2022.ZIP"
download.file( gus_url , tf_gus , mode = 'wb' )
unzipped_files_gus <- unzip( tf_gus , exdir = tempdir() )
xlsx_gus_fn <- grep( "\\.xlsx$" , unzipped_files_gus , value = TRUE )
xlsx_sheets <- excel_sheets( xlsx_gus_fn )
# read all sheets into a list of tibbles
gus_tbl_list <- lapply( xlsx_sheets , function( w ) read_excel( xlsx_gus_fn , sheet = w ) )
# convert all tibbles to data.frame objects
gus_df_list <- lapply( gus_tbl_list , data.frame )
# lowercase all column names
gus_df_list <-
lapply(
gus_df_list ,
function( w ){ names( w ) <- tolower( names( w ) ) ; w }
)
# add the excel tab source to each data.frame
for( i in seq( xlsx_sheets ) ) gus_df_list[[ i ]][ , 'source_tab' ] <- xlsx_sheets[ i ]
# determine which columns are in all tables
column_intersect <- Reduce( intersect , lapply( gus_df_list , names ) )
# determine which columns are in some but not all tables
column_union <- unique( unlist( lapply( gus_df_list , names ) ) )
# these columns will be discarded by stacking:
unique(
unlist(
lapply(
lapply( gus_df_list , names ) ,
function( w ) column_union[ !column_union %in% w ]
)
)
)
# stack all excel sheets, keeping only the columns that all tables have in common
gus_df <- Reduce( rbind , lapply( gus_df_list , function( w ) w[ column_intersect ] ) )
```
Download and import the survey of public employment & payroll, one record per function (not per unit):
```{r eval = FALSE , results = "hide" }
tf_apes <- tempfile()
apes_url <-
paste0(
"https://www2.census.gov/programs-surveys/apes/datasets/" ,
"2022/2022%20COG-E%20Individual%20Unit%20Files.zip"
)
download.file( apes_url , tf_apes , mode = 'wb' )
unzipped_files_apes <- unzip( tf_apes , exdir = tempdir() )
xlsx_apes_fn <- grep( "\\.xlsx$" , unzipped_files_apes , value = TRUE )
apes_tbl <- read_excel( xlsx_apes_fn )
apes_df <- data.frame( apes_tbl )
names( apes_df ) <- tolower( names( apes_df ) )
```
Review the non-matching records between these two tables, then merge:
```{r eval = FALSE , results = "hide" }
# all DEP School Districts and a third of Special Districts are not in the `apes_df`
table(
gus_df[ , 'census_id_gidid' ] %in% apes_df[ , 'individual.unit.id' ] ,
gus_df[ , 'source_tab' ] ,
useNA = 'always'
)
# state governments are not in the `gus_df`
table(
apes_df[ , 'individual.unit.id' ] %in% gus_df[ , 'census_id_gidid' ] ,
apes_df[ , 'type.of.government' ] ,
useNA = 'always'
)
# check for overlapping field names:
( overlapping_names <- intersect( names( apes_df ) , names( gus_df ) ) )
# rename the state column in `gus_df` to state abbreviation
names( gus_df )[ names( gus_df ) == 'state' ] <- 'stateab'
double_df <-
merge(
apes_df ,
gus_df ,
by.x = 'individual.unit.id' ,
by.y = 'census_id_gidid' ,
all.x = TRUE
)
stopifnot( nrow( double_df ) == nrow( apes_df ) )
# replace dots with underscores
names( double_df ) <- gsub( "\\." , "_" , names( double_df ) )
```
Keep either the one record per agency rows or the one record per function rows:
```{r eval = FALSE , results = "hide" }
# `Total - All Government Employment Functions` records sum to the same as all other records:
with( double_df , tapply( full_time_employees , grepl( "Total" , government_function ) , sum ) )
with( double_df , tapply( part_time_payroll , grepl( "Total" , government_function ) , sum ) )
# keep one record per government function (multiple records per agency):
cog_df <- subset( double_df , !grepl( "Total" , government_function ) )
# keep one record per government agency:
# cog_df <- subset( double_df , grepl( "Total" , government_function ) )
```
### Save Locally \ {-}
Save the object at any point:
```{r eval = FALSE , results = "hide" }
# cog_fn <- file.path( path.expand( "~" ) , "COG" , "this_file.rds" )
# saveRDS( cog_df , file = cog_fn , compress = FALSE )
```
Load the same object:
```{r eval = FALSE , results = "hide" }
# cog_df <- readRDS( cog_fn )
```
### Variable Recoding {-}
Add new columns to the data set:
```{r eval = FALSE , results = "hide" }
cog_df <-
transform(
cog_df ,
one = 1 ,
total_payroll = full_time_payroll + part_time_payroll ,
total_employees = full_time_employees + part_time_employees ,
any_full_time_employees = full_time_employees > 0
)
```
---
## Analysis Examples with base R \ {-}
### Unweighted Counts {-}
Count the unweighted number of records in the table, overall and by groups:
```{r eval = FALSE , results = "hide" }
nrow( cog_df )
table( cog_df[ , "type_of_government" ] , useNA = "always" )
```
### Descriptive Statistics {-}
Calculate the mean (average) of a linear variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
mean( cog_df[ , "full_time_employees" ] )
tapply(
cog_df[ , "full_time_employees" ] ,
cog_df[ , "type_of_government" ] ,
mean
)
```
Calculate the distribution of a categorical variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
prop.table( table( cog_df[ , "census_region" ] ) )
prop.table(
table( cog_df[ , c( "census_region" , "type_of_government" ) ] ) ,
margin = 2
)
```
Calculate the sum of a linear variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
sum( cog_df[ , "full_time_employees" ] )
tapply(
cog_df[ , "full_time_employees" ] ,
cog_df[ , "type_of_government" ] ,
sum
)
```
Calculate the median (50th percentile) of a linear variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
quantile( cog_df[ , "full_time_employees" ] , 0.5 )
tapply(
cog_df[ , "full_time_employees" ] ,
cog_df[ , "type_of_government" ] ,
quantile ,
0.5
)
```
### Subsetting {-}
Limit your `data.frame` to Elementary, Secondary, Higher, and Other Educational Government Agencies:
```{r eval = FALSE , results = "hide" }
sub_cog_df <- subset( cog_df , grepl( 'Education' , government_function ) )
```
Calculate the mean (average) of this subset:
```{r eval = FALSE , results = "hide" }
mean( sub_cog_df[ , "full_time_employees" ] )
```
### Measures of Uncertainty {-}
Calculate the variance, overall and by groups:
```{r eval = FALSE , results = "hide" }
var( cog_df[ , "full_time_employees" ] )
tapply(
cog_df[ , "full_time_employees" ] ,
cog_df[ , "type_of_government" ] ,
var
)
```
### Regression Models and Tests of Association {-}
Perform a t-test:
```{r eval = FALSE , results = "hide" }
t.test( full_time_employees ~ any_full_time_employees , cog_df )
```
Perform a chi-squared test of association:
```{r eval = FALSE , results = "hide" }
this_table <- table( cog_df[ , c( "any_full_time_employees" , "census_region" ) ] )
chisq.test( this_table )
```
Perform a generalized linear model:
```{r eval = FALSE , results = "hide" }
glm_result <-
glm(
full_time_employees ~ any_full_time_employees + census_region ,
data = cog_df
)
summary( glm_result )
```
---
## Replication Example {-}
This example matches excel cell "C17" of [Employment & Payroll Data by State and by Function](https://www2.census.gov/programs-surveys/apes/datasets/2022/2022_state_and_local.xlsx):
```{r eval = FALSE , results = "hide" }
financial_admin_df <- subset( cog_df , government_function == 'Financial Administration' )
stopifnot( sum( financial_admin_df[ , 'full_time_employees' ] ) == 401394 )
```
---
## Analysis Examples with `dplyr` \ {-}
The R `dplyr` library offers an alternative grammar of data manipulation to base R and SQL syntax. [dplyr](https://github.com/tidyverse/dplyr/) offers many verbs, such as `summarize`, `group_by`, and `mutate`, the convenience of pipe-able functions, and the `tidyverse` style of non-standard evaluation. [This vignette](https://cran.r-project.org/web/packages/dplyr/vignettes/dplyr.html) details the available features. As a starting point for COG users, this code replicates previously-presented examples:
```{r eval = FALSE , results = "hide" }
library(dplyr)
cog_tbl <- as_tibble( cog_df )
```
Calculate the mean (average) of a linear variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
cog_tbl %>%
summarize( mean = mean( full_time_employees ) )
cog_tbl %>%
group_by( type_of_government ) %>%
summarize( mean = mean( full_time_employees ) )
```
---
## Analysis Examples with `data.table` \ {-}
The R `data.table` library provides a high-performance version of base R's data.frame with syntax and feature enhancements for ease of use, convenience and programming speed. [data.table](https://r-datatable.com) offers concise syntax: fast to type, fast to read, fast speed, memory efficiency, a careful API lifecycle management, an active community, and a rich set of features. [This vignette](https://cran.r-project.org/web/packages/data.table/vignettes/datatable-intro.html) details the available features. As a starting point for COG users, this code replicates previously-presented examples:
```{r eval = FALSE , results = 'hide' }
library(data.table)
cog_dt <- data.table( cog_df )
```
Calculate the mean (average) of a linear variable, overall and by groups:
```{r eval = FALSE , results = 'hide' }
cog_dt[ , mean( full_time_employees ) ]
cog_dt[ , mean( full_time_employees ) , by = type_of_government ]
```
---
## Analysis Examples with `duckdb` \ {-}
The R `duckdb` library provides an embedded analytical data management system with support for the Structured Query Language (SQL). [duckdb](https://duckdb.org) offers a simple, feature-rich, fast, and free SQL OLAP management system. [This vignette](https://duckdb.org/docs/api/r) details the available features. As a starting point for COG users, this code replicates previously-presented examples:
```{r eval = FALSE , results = 'hide' }
library(duckdb)
con <- dbConnect( duckdb::duckdb() , dbdir = 'my-db.duckdb' )
dbWriteTable( con , 'cog' , cog_df )
```
Calculate the mean (average) of a linear variable, overall and by groups:
```{r eval = FALSE , results = 'hide' }
dbGetQuery( con , 'SELECT AVG( full_time_employees ) FROM cog' )
dbGetQuery(
con ,
'SELECT
type_of_government ,
AVG( full_time_employees )
FROM
cog
GROUP BY
type_of_government'
)
```