This repository has been archived by the owner on Dec 30, 2023. It is now read-only.
forked from ajdamico/asdfree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
15-censo.Rmd
414 lines (316 loc) · 11.9 KB
/
15-censo.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# Brazilian Censo Demografico (CENSO) {-}
[![Build Status](https://travis-ci.org/asdfree/censo.svg?branch=master)](https://travis-ci.org/asdfree/censo) [![Build status](https://ci.appveyor.com/api/projects/status/github/asdfree/censo?svg=TRUE)](https://ci.appveyor.com/project/ajdamico/censo)
*Contributed by Dr. Djalma Pessoa <<[email protected]>>*
Brazil's decennial census.
* One table with one row per household and a second table with one row per individual within each household. The 2000 Censo also includes a table with one record per family inside each household.
* An enumeration of the civilian non-institutional population of Brazil.
* Released decennially by IBGE since 2000, however earlier extracts are available from IPUMS International.
* Administered by the [Instituto Brasileiro de Geografia e Estatistica](http://www.ibge.gov.br/).
## Simplified Download and Importation {-}
The R `lodown` package easily downloads and imports all available CENSO microdata by simply specifying `"censo"` with an `output_dir =` parameter in the `lodown()` function. Depending on your internet connection and computer processing speed, you might prefer to run this step overnight.
```{r eval = FALSE }
library(lodown)
lodown( "censo" , output_dir = file.path( path.expand( "~" ) , "CENSO" ) )
```
`lodown` also provides a catalog of available microdata extracts with the `get_catalog()` function. After requesting the CENSO catalog, you could pass a subsetted catalog through the `lodown()` function in order to download and import specific extracts (rather than all available extracts).
```{r eval = FALSE , results = "hide" }
library(lodown)
# examine all available CENSO microdata files
censo_cat <-
get_catalog( "censo" ,
output_dir = file.path( path.expand( "~" ) , "CENSO" ) )
# 2010 only
censo_cat <- subset( censo_cat , year == 2010 )
# download the microdata to your local computer
censo_cat <- lodown( "censo" , censo_cat )
```
## Analysis Examples with the `survey` library \ {-}
Construct a complex sample survey design:
```{r eval = FALSE }
```
```{r eval = FALSE }
library(survey)
# choose columns to import from both household and person files
columns_to_import <-
c( 'v6531' , 'v6033' , 'v0640' , 'v0001' , 'v0601' )
# initiate a data.frame to stack all downloaded censo states
censo_df <- data.frame( NULL )
# only construct one censo design at a time (2000 and 2010 should not be stacked)
stopifnot( length( unique( censo_cat[ , 'year' ] ) ) == 1 )
# loop through all downloaded censo states
for( this_state in seq( nrow( censo_cat ) ) ){
# add the design information to the columns to import
these_columns_to_import <-
unique(
c(
columns_to_import ,
as.character(
censo_cat[ this_state , c( 'weight' , paste0( 'fpc' , 1:5 ) ) ]
)
)
)
# remove NAs
these_columns_to_import <- these_columns_to_import[ !is.na( these_columns_to_import ) ]
# load structure files, lowercase variable names, set unwanted columns to missing
dom_stru <- SAScii::parse.SAScii( censo_cat[ this_state , 'dom_sas' ] )
dom_stru$varname <- tolower( dom_stru$varname )
pes_stru <- SAScii::parse.SAScii( censo_cat[ this_state , 'pes_sas' ] )
pes_stru$varname <- tolower( pes_stru$varname )
# import fixed-width files
this_censo_dom_df <-
data.frame( readr::read_fwf(
censo_cat[ this_state , 'dom_file' ] ,
readr::fwf_widths(
abs( dom_stru$width ) , col_names = dom_stru[ , 'varname' ]
) ,
col_types =
paste0(
ifelse( !( dom_stru$varname %in% these_columns_to_import ) ,
"_" ,
ifelse( dom_stru$char , "c" , "d" )
) ,
collapse = ""
)
) )
this_censo_pes_df <-
data.frame( readr::read_fwf(
censo_cat[ this_state , 'pes_file' ] ,
readr::fwf_widths(
abs( pes_stru$width ) , col_names = pes_stru[ , 'varname' ]
) ,
col_types =
paste0(
ifelse( !( pes_stru$varname %in% these_columns_to_import ) ,
"_" ,
ifelse( pes_stru$char , "c" , "d" )
) ,
collapse = ""
)
) )
# add decimals
for( this_variable in these_columns_to_import ) {
if(
( this_variable %in% names( this_censo_dom_df ) ) &
!isTRUE( all.equal( 1 , dom_stru[ dom_stru$varname == this_variable , 'divisor' ] ) )
){
this_censo_dom_df[ , this_variable ] <-
dom_stru[ dom_stru$varname == this_variable , 'divisor' ] *
this_censo_dom_df[ , this_variable ]
}
if(
( this_variable %in% names( this_censo_pes_df ) ) &
!isTRUE( all.equal( 1 , pes_stru[ pes_stru$varname == this_variable , 'divisor' ] ) )
){
this_censo_pes_df[ , this_variable ] <-
pes_stru[ pes_stru$varname == this_variable , 'divisor' ] *
this_censo_pes_df[ , this_variable ]
}
}
# merge household and person tables
this_censo_df <- merge( this_censo_dom_df , this_censo_pes_df )
# confirm one record per person, with household information merged on
stopifnot( nrow( this_censo_df ) == nrow( this_censo_pes_df ) )
rm( this_censo_dom_df , this_censo_pes_df ) ; gc()
# stack the merged tables
censo_df <- rbind( censo_df , this_censo_df )
rm( this_censo_df ) ; gc()
}
# add a column of ones
censo_df[ , 'one' ] <- 1
# calculate the finite population correction for each stratum to construct a
# sampling design with weighting areas as strata and households as psu
# the real censo design is stratified with "setor censitarios" rather than
# "area de ponderacao" but those are not disclosed due to confidentiality
# v0010 is the person or household weight
# v0011 is the weighting area identifier
# both of these are specified inside `censo_cat[ c( 'fpc1' , 'weight' ) ]`
fpc_sums <- aggregate( v0010 ~ v0011 , data = censo_df , sum )
names( fpc_sums )[ 2 ] <- 'fpc'
censo_df <- merge( censo_df , fpc_sums ) ; gc()
censo_wgts <-
survey::bootweights(
strata = censo_df[ , censo_cat[ 1 , 'fpc1' ] ] ,
psu = censo_df[ , censo_cat[ 1 , 'fpc4' ] ] ,
replicates = 80 ,
fpc = censo_df[ , 'fpc' ]
)
# construct a complex survey design object
censo_design <-
survey::svrepdesign(
weight = ~ v0010 ,
repweights = censo_wgts$repweights ,
type = "bootstrap",
combined.weights = FALSE ,
scale = censo_wgts$scale ,
rscales = censo_wgts$rscales ,
data = censo_df
)
rm( censo_df , censo_wgts , fpc_sums ) ; gc()
```
### Variable Recoding {-}
Add new columns to the data set:
```{r eval = FALSE }
censo_design <-
update(
censo_design ,
nmorpob1 = ifelse( v6531 >= 0 , as.numeric( v6531 < 70 ) , NA ) ,
nmorpob2 = ifelse( v6531 >= 0 , as.numeric( v6531 < 80 ) , NA ) ,
nmorpob3 = ifelse( v6531 >= 0 , as.numeric( v6531 < 90 ) , NA ) ,
nmorpob4 = ifelse( v6531 >= 0 , as.numeric( v6531 < 100 ) , NA ) ,
nmorpob5 = ifelse( v6531 >= 0 , as.numeric( v6531 < 140 ) , NA ) ,
nmorpob6 = ifelse( v6531 >= 0 , as.numeric( v6531 < 272.50 ) , NA ) ,
sexo = factor( v0601 , labels = c( "masculino" , "feminino" ) ) ,
state_name =
factor(
v0001 ,
levels = c( 11:17 , 21:29 , 31:33 , 35 , 41:43 , 50:53 ) ,
labels = c( "Rondonia" , "Acre" , "Amazonas" ,
"Roraima" , "Para" , "Amapa" , "Tocantins" ,
"Maranhao" , "Piaui" , "Ceara" , "Rio Grande do Norte" ,
"Paraiba" , "Pernambuco" , "Alagoas" , "Sergipe" ,
"Bahia" , "Minas Gerais" , "Espirito Santo" ,
"Rio de Janeiro" , "Sao Paulo" , "Parana" ,
"Santa Catarina" , "Rio Grande do Sul" ,
"Mato Grosso do Sul" , "Mato Grosso" , "Goias" ,
"Distrito Federal" )
)
)
```
### Unweighted Counts {-}
Count the unweighted number of records in the survey sample, overall and by groups:
```{r eval = FALSE , results = "hide" }
sum( weights( censo_design , "sampling" ) != 0 )
svyby( ~ one , ~ state_name , censo_design , unwtd.count )
```
### Weighted Counts {-}
Count the weighted size of the generalizable population, overall and by groups:
```{r eval = FALSE , results = "hide" }
svytotal( ~ one , censo_design )
svyby( ~ one , ~ state_name , censo_design , svytotal )
```
### Descriptive Statistics {-}
Calculate the mean (average) of a linear variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
svymean( ~ v6033 , censo_design )
svyby( ~ v6033 , ~ state_name , censo_design , svymean )
```
Calculate the distribution of a categorical variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
svymean( ~ sexo , censo_design )
svyby( ~ sexo , ~ state_name , censo_design , svymean )
```
Calculate the sum of a linear variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
svytotal( ~ v6033 , censo_design )
svyby( ~ v6033 , ~ state_name , censo_design , svytotal )
```
Calculate the weighted sum of a categorical variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
svytotal( ~ sexo , censo_design )
svyby( ~ sexo , ~ state_name , censo_design , svytotal )
```
Calculate the median (50th percentile) of a linear variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
svyquantile( ~ v6033 , censo_design , 0.5 )
svyby(
~ v6033 ,
~ state_name ,
censo_design ,
svyquantile ,
0.5 ,
ci = TRUE ,
keep.var = TRUE
)
```
Estimate a ratio:
```{r eval = FALSE , results = "hide" }
svyratio(
numerator = ~ nmorpob1 ,
denominator = ~ nmorpob1 + one ,
censo_design ,
na.rm = TRUE
)
```
### Subsetting {-}
Restrict the survey design to married persons:
```{r eval = FALSE , results = "hide" }
sub_censo_design <- subset( censo_design , v0640 == 1 )
```
Calculate the mean (average) of this subset:
```{r eval = FALSE , results = "hide" }
svymean( ~ v6033 , sub_censo_design )
```
### Measures of Uncertainty {-}
Extract the coefficient, standard error, confidence interval, and coefficient of variation from any descriptive statistics function result, overall and by groups:
```{r eval = FALSE , results = "hide" }
this_result <- svymean( ~ v6033 , censo_design )
coef( this_result )
SE( this_result )
confint( this_result )
cv( this_result )
grouped_result <-
svyby(
~ v6033 ,
~ state_name ,
censo_design ,
svymean
)
coef( grouped_result )
SE( grouped_result )
confint( grouped_result )
cv( grouped_result )
```
Calculate the degrees of freedom of any survey design object:
```{r eval = FALSE , results = "hide" }
degf( censo_design )
```
Calculate the complex sample survey-adjusted variance of any statistic:
```{r eval = FALSE , results = "hide" }
svyvar( ~ v6033 , censo_design )
```
Include the complex sample design effect in the result for a specific statistic:
```{r eval = FALSE , results = "hide" }
# SRS without replacement
svymean( ~ v6033 , censo_design , deff = TRUE )
# SRS with replacement
svymean( ~ v6033 , censo_design , deff = "replace" )
```
Compute confidence intervals for proportions using methods that may be more accurate near 0 and 1. See `?svyciprop` for alternatives:
```{r eval = FALSE , results = "hide" }
svyciprop( ~ nmorpob6 , censo_design ,
method = "likelihood" , na.rm = TRUE )
```
### Regression Models and Tests of Association {-}
Perform a design-based t-test:
```{r eval = FALSE , results = "hide" }
svyttest( v6033 ~ nmorpob6 , censo_design )
```
Perform a chi-squared test of association for survey data:
```{r eval = FALSE , results = "hide" }
svychisq(
~ nmorpob6 + sexo ,
censo_design
)
```
Perform a survey-weighted generalized linear model:
```{r eval = FALSE , results = "hide" }
glm_result <-
svyglm(
v6033 ~ nmorpob6 + sexo ,
censo_design
)
summary( glm_result )
```
## Poverty and Inequality Estimation with `convey` \ {-}
The R `convey` library estimates measures of income concentration, poverty, inequality, and wellbeing. [This textbook](https://guilhermejacob.github.io/context/) details the available features. As a starting point for CENSO users, this code calculates the gini coefficient on complex sample survey data:
```{r eval = FALSE , results = "hide" }
library(convey)
censo_design <- convey_prep( censo_design )
sub_censo_design <-
subset( censo_design , v6531 >= 0 )
svygini( ~ v6531 , sub_censo_design , na.rm = TRUE )
```
---
## Replication Example {-}
```{r eval = FALSE , results = "hide" }
```