-
Notifications
You must be signed in to change notification settings - Fork 449
/
pnad.Rmd
475 lines (332 loc) · 13.2 KB
/
pnad.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# Pesquisa Nacional por Amostra de Domicilios (PNAD) {-}
[![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/pnad/actions"><img src="https://github.com/asdfree/pnad/actions/workflows/r.yml/badge.svg" alt="Github Actions Badge"></a>
Brazil's principal labor force survey, measuring education, employment, income, housing characteristics.
* One consolidated table with one row per individual within each sampled household.
* A complex sample survey designed to generalize to the civilian non-institutional population of Brazil.
* Released quarterly since 2012, with microdata available both quarterly and annually.
* Administered by the [Instituto Brasileiro de Geografia e Estatistica](http://www.ibge.gov.br/).
---
Please skim before you begin:
1. [Conceitos e métodos](https://www.ibge.gov.br/estatisticas/sociais/trabalho/17270-pnad-continua.html?=&t=conceitos-e-metodos)
2. [Wikipedia Entry](https://pt.wikipedia.org/wiki/Pesquisa_Nacional_por_Amostra_de_Domic%C3%ADlios)
3. A haiku regarding this microdata:
```{r}
# mineiro data
# love verdade gave to me
# twelve karaoke..
```
---
## Download, Import, Preparation {-}
Download and import the dictionary file:
```{r eval = FALSE , results = "hide" }
dictionary_tf <- tempfile()
dictionary_url <-
paste0(
"https://ftp.ibge.gov.br/Trabalho_e_Rendimento/" ,
"Pesquisa_Nacional_por_Amostra_de_Domicilios_continua/" ,
"Trimestral/Microdados/Documentacao/Dicionario_e_input_20221031.zip"
)
download.file( dictionary_url , dictionary_tf , mode = 'wb' )
dictionary_files <- unzip( dictionary_tf , exdir = tempdir() )
sas_fn <- grep( '\\.sas$' , dictionary_files , value = TRUE )
sas_lines <- readLines( sas_fn , encoding = 'latin1' )
```
Determine fixed-width file positions from the SAS import script:
```{r eval = FALSE , results = "hide" }
sas_start <- grep( '@0001' , sas_lines )
sas_end <- grep( ';' , sas_lines )
sas_end <- sas_end[ sas_end > sas_start ][ 1 ]
sas_lines <- sas_lines[ seq( sas_start , sas_end - 1 ) ]
# remove SAS comments
sas_lines <- gsub( "\\/\\*(.*)" , "" , sas_lines )
# remove multiple spaces and spaces at the end of each string
sas_lines <- gsub( "( +)" , " " , sas_lines )
sas_lines <- gsub( " $" , "" , sas_lines )
sas_df <-
read.table(
textConnection( sas_lines ) ,
sep = ' ' ,
col.names = c( 'position' , 'column_name' , 'length' ) ,
header = FALSE
)
sas_df[ , 'character' ] <- grepl( '\\$' , sas_df[ , 'length' ] )
sas_df[ , 'position' ] <- as.integer( gsub( "\\@" , "" , sas_df[ , 'position' ] ) )
sas_df[ , 'length' ] <- as.integer( gsub( "\\$" , "" , sas_df[ , 'length' ] ) )
stopifnot(
sum( sas_df[ , 'length' ] ) ==
( sas_df[ nrow( sas_df ) , 'position' ] + sas_df[ nrow( sas_df ) , 'length' ] - 1 )
)
```
Download the latest quarterly file:
```{r eval = FALSE , results = "hide" }
this_tf <- tempfile()
this_url <-
paste0(
"https://ftp.ibge.gov.br/Trabalho_e_Rendimento/" ,
"Pesquisa_Nacional_por_Amostra_de_Domicilios_continua/" ,
"Trimestral/Microdados/2023/PNADC_012023.zip"
)
download.file( this_url , this_tf , mode = 'wb' )
```
Import the latest quarterly file:
```{r eval = FALSE , results = "hide" }
library(readr)
pnad_tbl <-
read_fwf(
this_tf ,
fwf_widths(
widths = sas_df[ , 'length' ] ,
col_names = sas_df[ , 'column_name' ]
) ,
col_types =
paste0( ifelse( sas_df[ , 'character' ] , "c" , "d" ) , collapse = '' )
)
pnad_df <- data.frame( pnad_tbl )
names( pnad_df ) <- tolower( names( pnad_df ) )
pnad_df[ , 'one' ] <- 1
```
### Save Locally \ {-}
Save the object at any point:
```{r eval = FALSE , results = "hide" }
# pnad_fn <- file.path( path.expand( "~" ) , "PNAD" , "this_file.rds" )
# saveRDS( pnad_df , file = pnad_fn , compress = FALSE )
```
Load the same object:
```{r eval = FALSE , results = "hide" }
# pnad_df <- readRDS( pnad_fn )
```
### Survey Design Definition {-}
Construct a complex sample survey design:
```{r eval = FALSE , results = "hide" }
library(survey)
pnad_design <-
svrepdesign(
data = pnad_df ,
weight = ~ v1028 ,
type = 'bootstrap' ,
repweights = 'v1028[0-9]+' ,
mse = TRUE ,
)
```
### Variable Recoding {-}
Add new columns to the data set:
```{r eval = FALSE , results = "hide" }
pnad_design <-
update(
pnad_design ,
pia = as.numeric( v2009 >= 14 )
)
pnad_design <-
update(
pnad_design ,
ocup_c = ifelse( pia == 1 , as.numeric( vd4002 %in% 1 ) , NA ) ,
desocup30 = ifelse( pia == 1 , as.numeric( vd4002 %in% 2 ) , NA )
)
pnad_design <-
update(
pnad_design ,
uf_name =
factor(
as.numeric( uf ) ,
levels =
c(11L, 12L, 13L, 14L, 15L, 16L, 17L, 21L, 22L, 23L, 24L, 25L,
26L, 27L, 28L, 29L, 31L, 32L, 33L, 35L, 41L, 42L, 43L, 50L, 51L,
52L, 53L) ,
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")
) ,
age_categories = factor( 1 + findInterval( v2009 , seq( 5 , 60 , 5 ) ) ) ,
male = as.numeric( v2007 == 1 ) ,
region = substr( uf , 1 , 1 ) ,
# calculate usual income from main job
# (rendimento habitual do trabalho principal)
vd4016n = ifelse( pia %in% 1 & vd4015 %in% 1 , vd4016 , NA ) ,
# calculate effective income from main job
# (rendimento efetivo do trabalho principal)
vd4017n = ifelse( pia %in% 1 & vd4015 %in% 1 , vd4017 , NA ) ,
# calculate usual income from all jobs
# (variavel rendimento habitual de todos os trabalhos)
vd4019n = ifelse( pia %in% 1 & vd4015 %in% 1 , vd4019 , NA ) ,
# calculate effective income from all jobs
# (rendimento efetivo do todos os trabalhos)
vd4020n = ifelse( pia %in% 1 & vd4015 %in% 1 , vd4020 , NA ) ,
# determine the potential labor force
pea_c = as.numeric( ocup_c == 1 | desocup30 == 1 )
)
```
---
## Analysis Examples with the `survey` library \ {-}
### Unweighted Counts {-}
Count the unweighted number of records in the survey sample, overall and by groups:
```{r eval = FALSE , results = "hide" }
sum( weights( pnad_design , "sampling" ) != 0 )
svyby( ~ one , ~ uf_name , pnad_design , unwtd.count )
```
### Weighted Counts {-}
Count the weighted size of the generalizable population, overall and by groups:
```{r eval = FALSE , results = "hide" }
svytotal( ~ one , pnad_design )
svyby( ~ one , ~ uf_name , pnad_design , svytotal )
```
### Descriptive Statistics {-}
Calculate the mean (average) of a linear variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
svymean( ~ vd4020n , pnad_design , na.rm = TRUE )
svyby( ~ vd4020n , ~ uf_name , pnad_design , svymean , na.rm = TRUE )
```
Calculate the distribution of a categorical variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
svymean( ~ age_categories , pnad_design )
svyby( ~ age_categories , ~ uf_name , pnad_design , svymean )
```
Calculate the sum of a linear variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
svytotal( ~ vd4020n , pnad_design , na.rm = TRUE )
svyby( ~ vd4020n , ~ uf_name , pnad_design , svytotal , na.rm = TRUE )
```
Calculate the weighted sum of a categorical variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
svytotal( ~ age_categories , pnad_design )
svyby( ~ age_categories , ~ uf_name , pnad_design , svytotal )
```
Calculate the median (50th percentile) of a linear variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
svyquantile( ~ vd4020n , pnad_design , 0.5 , na.rm = TRUE )
svyby(
~ vd4020n ,
~ uf_name ,
pnad_design ,
svyquantile ,
0.5 ,
ci = TRUE , na.rm = TRUE
)
```
Estimate a ratio:
```{r eval = FALSE , results = "hide" }
svyratio(
numerator = ~ ocup_c ,
denominator = ~ pea_c ,
pnad_design ,
na.rm = TRUE
)
```
### Subsetting {-}
Restrict the survey design to employed persons:
```{r eval = FALSE , results = "hide" }
sub_pnad_design <- subset( pnad_design , ocup_c == 1 )
```
Calculate the mean (average) of this subset:
```{r eval = FALSE , results = "hide" }
svymean( ~ vd4020n , sub_pnad_design , na.rm = TRUE )
```
### 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( ~ vd4020n , pnad_design , na.rm = TRUE )
coef( this_result )
SE( this_result )
confint( this_result )
cv( this_result )
grouped_result <-
svyby(
~ vd4020n ,
~ uf_name ,
pnad_design ,
svymean ,
na.rm = TRUE
)
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( pnad_design )
```
Calculate the complex sample survey-adjusted variance of any statistic:
```{r eval = FALSE , results = "hide" }
svyvar( ~ vd4020n , pnad_design , na.rm = TRUE )
```
Include the complex sample design effect in the result for a specific statistic:
```{r eval = FALSE , results = "hide" }
# SRS without replacement
svymean( ~ vd4020n , pnad_design , na.rm = TRUE , deff = TRUE )
# SRS with replacement
svymean( ~ vd4020n , pnad_design , na.rm = TRUE , 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( ~ male , pnad_design ,
method = "likelihood" )
```
### Regression Models and Tests of Association {-}
Perform a design-based t-test:
```{r eval = FALSE , results = "hide" }
svyttest( vd4020n ~ male , pnad_design )
```
Perform a chi-squared test of association for survey data:
```{r eval = FALSE , results = "hide" }
svychisq(
~ male + age_categories ,
pnad_design
)
```
Perform a survey-weighted generalized linear model:
```{r eval = FALSE , results = "hide" }
glm_result <-
svyglm(
vd4020n ~ male + age_categories ,
pnad_design
)
summary( glm_result )
```
---
## Replication Example {-}
This example matches statistics and coefficients of variation from [Tabela 4092 - Pessoas de 14 anos ou mais de idade, por condição em relação à força de trabalho e condição de ocupação](https://sidra.ibge.gov.br/tabela/4092):
```{r eval = FALSE , results = "hide" }
nationwide_adult_population <- svytotal( ~ pia , pnad_design , na.rm = TRUE )
stopifnot( round( coef( nationwide_adult_population ) / 1000000 , 3 ) == 174.228 )
stopifnot( round( cv( nationwide_adult_population ) / 1000000 , 3 ) == 0 )
nationwide_labor_force <- svytotal( ~ pea_c , pnad_design , na.rm = TRUE )
stopifnot( round( coef( nationwide_labor_force ) / 1000000 , 3 ) == 107.257 )
stopifnot( round( cv( nationwide_labor_force ) * 100 , 1 ) == 0.2 )
nationwide_employed <- svytotal( ~ ocup_c , pnad_design , na.rm = TRUE )
stopifnot( round( coef( nationwide_employed ) / 1000000 , 3 ) == 97.825 )
stopifnot( round( cv( nationwide_employed ) * 100 , 1 ) == 0.2 )
nationwide_unemployed <- svytotal( ~ desocup30 , pnad_design , na.rm = TRUE )
stopifnot( round( coef( nationwide_unemployed ) / 1000000 , 3 ) == 9.432 )
stopifnot( round( cv( nationwide_unemployed ) * 100 , 1 ) == 1.2 )
nationwide_not_in_labor_force <-
svytotal( ~ as.numeric( pia & !pea_c ) , pnad_design , na.rm = TRUE )
stopifnot( round( coef( nationwide_not_in_labor_force ) / 1000000 , 3 ) == 66.972 )
stopifnot( round( cv( nationwide_not_in_labor_force ) * 100 , 1 ) == 0.3 )
```
---
## 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 PNAD users, this code calculates the gini coefficient on complex sample survey data:
```{r eval = FALSE , results = "hide" }
library(convey)
pnad_design <- convey_prep( pnad_design )
svygini( ~ vd4020n , pnad_design , na.rm = TRUE )
```
---
## Analysis Examples with `srvyr` \ {-}
The R `srvyr` library calculates summary statistics from survey data, such as the mean, total or quantile using [dplyr](https://github.com/tidyverse/dplyr/)-like syntax. [srvyr](https://github.com/gergness/srvyr) allows for the use of many verbs, such as `summarize`, `group_by`, and `mutate`, the convenience of pipe-able functions, the `tidyverse` style of non-standard evaluation and more consistent return types than the `survey` package. [This vignette](https://cran.r-project.org/web/packages/srvyr/vignettes/srvyr-vs-survey.html) details the available features. As a starting point for PNAD users, this code replicates previously-presented examples:
```{r eval = FALSE , results = "hide" }
library(srvyr)
pnad_srvyr_design <- as_survey( pnad_design )
```
Calculate the mean (average) of a linear variable, overall and by groups:
```{r eval = FALSE , results = "hide" }
pnad_srvyr_design %>%
summarize( mean = survey_mean( vd4020n , na.rm = TRUE ) )
pnad_srvyr_design %>%
group_by( uf_name ) %>%
summarize( mean = survey_mean( vd4020n , na.rm = TRUE ) )
```