-
Notifications
You must be signed in to change notification settings - Fork 4
/
Tutorial_Complex_sampling_R.Rmd
698 lines (441 loc) · 21.5 KB
/
Tutorial_Complex_sampling_R.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
---
output:
knitrBootstrap::bootstrap_document:
title: "Introducción al muestreo complejo en R"
theme: flatly
highlight: github
theme.chooser: TRUE
highlight.chooser: TRUE
---
#Tutorial de muestreo en R
**Fecha: `r as.character(format(Sys.Date(), format="%B %d, %Y"))`**
**Por Felipe Jiménez**
##Introducción
El presente tutorial tiene como objetivo principal el introducir al usuario en el muestreo simple y complejo en el ambiente de programación analítica R.Se cubren los siguientes temas:
* La selección de tamaños de muestra simples(`base` y `dplyr`),
* selección sistemática y cálculo de tamaños de muestra(`SamplinUtil`),
* cálculo de intervalos de confianza(`DescTools`),
* selección de muestras con PPT (`pps`),
* Muestreo complejo con el paquete ` survey `.
* Comparación de los resultados arrojados en R con información oficial de la Encuesta de Hogares del INEC.
##Configuración de R y Rstudio
El primer paso para iniciar con el tutorial es instalar [la consola de R](http://cran.rstudio.com/)(En el triste caso de aún no contar con él).
Posteriormente, es altamente recomendado utilizar el IDE [Rstudio](http://www.rstudio.com/products/rstudio/download/), para una mayor facilidad en el desarrollo de las aplicaciones.
Una vez con la instalación de nuestras dos herramientas, procedemos a crear un nuevo documento [Rmarkdown](http://rmarkdown.rstudio.com/) Y escogemos las opciones por defecto, como se ilustra en la siguiente figura:
![Rmarkdown](https://www.dropbox.com/s/aes3xp4xs2zrpx7/Captura1.png?dl=1)
Una vez abierto el nuevo documento R markdown, guardarlo y a continuación borrar el código que trae por defecto como ejemplo, a excepción del encabezado encerrado con tres slash (`---`) al inicio del documento.
-----------------------------------------------------------------------------
## Ejercicios
### Selección de muestras simples
**Muestreo irrestricto Aleatorio[(MIA)](http://www.virtual.unal.edu.co/cursos/sedes/manizales/4030006/lecciones/capituloseis/6_5.html)**:
El R Base contiene la útil función `sample` en la que se pueden obtener muestras aleatorias con o sin reemplazo de manera sencilla.
Vamos a cargar un dataset para ejemplificar y a cuantificar sus dimensiones:
```{r EJ1.0}
crime<-data.frame(crimtab)
dim(crime)
```
Como podemos ver, el dataset `crime` contiene `r dim(crime)[1] ` filas y `r dim(crime)[2] ` columnas.Seguidamente seleccionamos una muestra de
30 casos sin reemplazo:
```{r EJ1.1}
#Selección de la muestra
#Tamaño de la muestra
n<-30
muestramia<- sample(1:nrow(crime),n,replace=FALSE)
muestramia
#Asignar los elementos de la muestra al data frame de datos
crimemuestramia<- crime[muestramia, ]
head(crimemuestramia)
```
#### Selección de muestras simples con `dplyr`
Una forma más sencilla de obtener una muestra es con el paquete `dplyr`.Este paquete es sumamente útil para el tratamiento de datos, adicionalmente contiene una función para obtener muestras simples de un data frame:
```{r 1.2,message=FALSE}
library(dplyr)
#Muestra sin reemplazo
crimemuestramia2<- crime %.%
sample_n(size=n,replace=FALSE)
head(crimemuestramia2)
#Muestra con pesos
crimemuestramia3<- crime %.%
sample_n(size=n,weight=Freq)
head(crimemuestramia3)
#Muestra con una proporción de casos
crimemuestramia4<- crime %.%
sample_frac(0.05)
head(crimemuestramia4);dim(crimemuestramia4)
```
--------------------------------------------------------------------------
### Selección de muestras sistemáticas(Instalación del paquete `SamplingUtils`)
Para el ejemplo del muestreo sistemático utilizaremos la función `sys.sample` del paquete `SamplingUtil`.Para instalar este paquete, se debe inicialmente instalar el paquete `devtools` ya que no se encuentra en CRAN.Las instrucciones son las siguientes:
**Instalar devtools:**`install.packages("devtools")`
**Cargar libreria:** `library(devtools)`
**Instalar SamplingUtils:**`install_github("DFJL/SamplingUtils")`
De esta manera podemos proceder a generar la muestra sistemática:
```{r EJ1.2}
#Cargar libreria:
library(SamplingUtil)
muestrasis<- sys.sample(nrow(crime),30)
muestrasis
#Asignar los elementos de la muestra al data frame de datos
crimemuestrasis<- crime[muestrasis, ]
head(crimemuestrasis)
```
--------------------------------------------------------------------------------
### Tamaños de muestra simples
En este tutorial veremos tres variantes para cálculo de tamaño muestral asumiendo MIA.Para esto, utilizaremos la data de la ENAHO 2013 y la función `nsize()` incluída en el paquete `SamplingUtil`.
Como variable continua se utilizará la Cantidad de personas del hogar (**TamHog**), para el ejemplo de proporciones, se creará la variable Proporción de Hogares Unipersonales.
1. **Error relativo para variables continuas.**
se desea conocer el tamaño de muestra para que el error relativo no supere el 5%, con un alpha de 5%.
```{r EJ3.1,message=FALSE}
#Generando df de ENAHO2013 a nivel de hogar
df<- ENAHO2013 %.% #Define nuevo data frame
mutate(TamHog=as.numeric(TamHog), #Convierte TamHog a numérica
phu=ifelse(TamHog>1,0,1)) %.% #Crea variable de prop Hog. Unipersonales.
select(FACTOR:ZONA,TamHog,phu,-REGION) %.% #Selecciona variables de interés.
group_by(SEGMENTO,CUESTIONARIO,HOGAR,ZONA) %.% #Genera esquema de agrupación.
summarise(TamHog=mean(TamHog), #Cálculo de variables sumarizadas.
phu=mean(phu)) %.%
mutate(id=paste0(SEGMENTO,CUESTIONARIO,HOGAR,ZONA)) #Genera id único para uso posterior.
#Cálculo del tamaño de muestra con error relativo
#Error relativo
r<-0.05
nsizeR<- nsize(x=df$TamHog,r=r,alpha=0.05)
nsizeR
```
2. **Error absoluto para variables continuas.**
```{r EJ3.2}
#Cálculo del tamaño de muestra con error absoluto
#Igualar el error absoluto con el error relativo
abs<-mean(df$TamHog)*r
nsizeA<- nsize(x=df$TamHog,abs=abs,alpha=0.05)
nsizeA
```
3. **Error relativo para variables dicotómicas.**
```{r EJ3.3}
#Cálculo de tamaño de muestra para proporción
nsizeP<- nsize(x=df$phu,abs=0.02,alpha=0.05)
nsizeP
```
### Tamaños de muestra estratificados
1. **Asignación proporcional.**
```{r EJ3.4}
#Cálculo de las proporciones por estrato
Estratos<- df %.%
select(ZONA,TamHog) %.%
group_by(ZONA) %.%
summarise(n=n(),
s=sd(TamHog)) %.%
mutate(p=n/sum(n))
Estratos
#Asignación de la muestra proporcional a los estratos
nsizeProp<-nstrata(nsizeR[[2]],Estratos[,4],method="proportional")
nsizeProp
```
2. **Asignación óptima.**
```{r EJ3.5}
#Asignación de la muestra óptima a los estratos
#Costo de entrevista por estrato
ch<-c(5,10)
nsizeOpt<-nstrata(nsizeR[[2]],Estratos[,4],Estratos[,3],ch,method="optimal")
nsizeOpt
```
3. **Asignación de Neyman.**
```{r EJ3.6}
#Asignación de la muestra óptima a los estratos(asume costos iguales)
nsizeNeyman<-nstrata(nsizeR[[2]],Estratos[,4],Estratos[,3],method="neyman")
nsizeNeyman
```
--------------------------------------------------------------------------------
### Cálculo de intervalos de confianza asumiendo MIA
En R existen múltiples posibilidades de calcular los intervalos de confianza.Se utilizará el paquete `DescTools` para este propósito.Este paquete contiene muchas funciones misceláneas de las tareas estadísticas típicas.
Calcularemos el intervalo de confianza para la media del Tamaño del hogar, con el tamaño de muestra obtenida en el ejercicio anterior y posteriormente se comparará el error obtenido(suponiendo que el valor verdadero es el de total de la encuesta)
```{r 4.1}
#Muestra sin reemplazo
muestra<- df %.%
sample_n(size=nsizeR[[2]],replace=FALSE)
#Carga de paquete DescTools
library(DescTools)
#Intervalos de confianza 95% clásicos
ICTamHog<- MeanCI(muestra$TamHog, trim = 0,conf.level = 0.95, na.rm = FALSE)
ICTamHog
#Media del total de la encuesta
mean(df$TamHog)
#Diferencia relativa
difR<-paste0(abs(round((ICTamHog[1]-mean(df$TamHog))/mean(df$TamHog),3))*100,"%")
```
De esta manera, con este ejercicio comprobamos que el valor estimado cumple con los requisitos del error relativo deseado en el cálculo del tamaño muestral, ya que la diferencia fue de **`r difR`** inferior al `r r*100 ` % deseado.
### Selección de muestra con ppt(Paquete `pps`)
Hemos abarcado aspectos básicos del muestreo de elementos.A partir de ahora veremos algunos ejemplos de muestreo complejo.
Existen diversos paquetes para selecciones de muestras complejas en R, como el `sampling` o el `samplingbook`.En este caso se utilizará el `pps` que se concentra en muestreo mediante ppt y permite la selección sistemática estratificada.
En el siguiente ejercicio se seleccionará una muestra de UPM utilizando como tamaño la cantidad de hogares, estratificada por Zona,utilizando como base el tamaño de muestra ya calculado para la variable Tamaño del hogar.
Se debe obtener una muestra proporcional para cada estrato y seleccionar en cada conglomerado una submuestra de 5 hogares.
```{r 5.1}
#Generar el dataframe de UPMS y su respectivo tamaño
UPMs<- df %.%
mutate(TamHog=as.numeric(TamHog)) %.%
select(SEGMENTO,ZONA,TamHog) %.%
group_by(SEGMENTO,ZONA) %.%
summarise(Mta=n()) %.%
arrange(ZONA)
head(UPMs)
#Se asigna proporcionalmente la muestra a cada estrato
#Recordemos la distribución proporcional de los estratos:
nsizeProp
#Cálculo del número de UPMs por estrato
b<-5
aurbano<- ceiling(nsizeProp[1]/b)
arural<- ceiling(nsizeProp[2]/b)
#Unir en un solo objeto para facilitar input de función
asizeppt<-rbind(aurbano,arural)
asizeppt
#Selección de la muestra con PPT(sistemática)
library(pps)
muestrappt<-ppssstrat(UPMs$Mta,UPMs$ZONA,asizeppt)
muestraUPMs<-UPMs[muestrappt,]
#Muestra de la selección
head(muestraUPMs)
tail(muestraUPMs)
#Verificar selección por estrato
Freq(muestraUPMs$ZONA)
#Procedimiento para seleccionar submuestras en cada cluster de tamaño fijo
#Listado de segmentos seleccionados
segs<- unique(muestraUPMs$SEGMENTO)
sample<- list()
#Identifica el número de columna del id(se requiere para el ciclo)
idcolnum<-which( colnames(df)=="id" )
#Ciclo para seleccionar la muestra en cada segmento
for(i in 1:length(segs)){
subsample<-df[which(df$SEGMENTO==segs[i]),]
sample[[i]]<-sys.sample(nrow(subsample),b)
#Previene de los números que se pasan del total del segmento
#if(sample[[i]][b]>nrow(subsample)){
# sample[[i]][b]<-1
# }
#Asigna en cada elemento de las submuestras los elem. seleccionados
sample[[i]]<-subsample[unlist(sample[[i]]),idcolnum]
}
#Genera el data frame de ids seleccionados(ya que estaban en una lista)
sampledf<-data.frame(id=unlist(sample))
#Uniendo el data frame de datos con la muestra seleccionada mendiante la llave creada
muestrappt<-inner_join(unique(sampledf),unique(df),by="id")
#Verificar el procedimiento
head(muestrappt)
Freq(muestrappt$ZONA)
```
### Diseños de muestreo Complejos
#### Especificación diseños muestrales complejos(paquete `survey`)
Un paquete robusto para el cálculo correcto de estadísticos en diseños complejos es el `survey`.A continuación se ejemplifica la función `svydesign`, la cuál establece los diferentes parámetros para poder calcular los errores muestrales adecuadamente.Inicialmente utilizaremos la muestra con ppt seleccionada en el ejercicio anterior.
```{r EJ 6.1,message=FALSE}
#Generar probabilidades
#Recordemos las medidas de tamaño por UPM:
UPMs
#Cálculo de prob en Primera etapa
#Estrato Urbano
UPMU<- UPMs %.%
filter(ZONA=="Urbana") %.%
group_by(ZONA) %.%
mutate(fa=Mta/(sum(Mta)/aurbano),
fb=b/Mta)
#Estrato Rural
UPMR<- UPMs %.%
filter(ZONA=="Rural") %.%
group_by(ZONA) %.%
mutate(fa=Mta/(sum(Mta)/arural),
fb=b/Mta)
#Unir ambos estratos
UPMs <- rbind(UPMU,UPMR)
#Incluir probabilidades en data frame de muestra
muestrappt2<- left_join(muestrappt,UPMs,by=c("SEGMENTO","ZONA"))
#Cargar paquete de muestreo complejo
library(survey)
#Establecer el diseño muestral
design1<-svydesign(data=muestrappt2,id=~SEGMENTO+id,
strata=~ZONA,pps="brewer",prob=~fa+fb)
#Resumen del diseño
summary(design1)
```
#### Estadísticos en diseños muestrales complejos
```{r EJ 6.2,message=FALSE}
#Calculando estadísticos de TamHog
TamHogmc<- svymean(~TamHog,design=design1,deff=TRUE)
#Media del Tamaño del hogar
TamHogmc
#Efecto del diseño
deff(TamHogmc)
#Intervalo de confianza
confint(TamHogmc)
#Coeficiente de variación
cv(TamHogmc)
#Diferencia relativa
difRc<-paste0(abs(round((TamHogmc[1]-mean(df$TamHog))/mean(df$TamHog),3))*100,"%")
```
De esta manera, con este ejercicio comprobamos que el valor estimado cumple con los requisitos del error relativo deseado en el cálculo del tamaño muestral, ya que la diferencia fue de **`r difRc`** inferior al `r r*100 ` % deseado.
#### Ejemplo con diseño complejo real
Finalmente, se desarrollará un ejemplo con un diseño complejo real,utilizando la ENAHO 2012.
El diseño muestral se detalla a continuación:
**Diseño muestral:** diseño probabilístico, estratificado y bietápico. En la primera etapa se seleccionaron segmentos censales o unidades primarias de muestreo (UPM) con probabilidad proporcional al tamaño (PPT), y en la segunda etapa se seleccionaron las viviendas o unidades secundarias de muestreo (USM) con probabilidades iguales de selección dentro de cada segmento, mediante muestreo sistemático con arranque aleatorio.
**Dominios de estudio:** las seis regiones de planificación y las zonas urbana y rural.
```{r EJ 6.3,message=FALSE}
#Objetos para generar variables(debido a que el Dataframe de ENAHO2012 tiene las labels del SPSS y no los valores)
profesionales<- c("Profesionales científicos e intelectuales")
tecnicos<- c("Técnicos y profesionales de nivel medio")
#Generando df de ENAHO2012 a nivel de hogar
df12<- ENAHO2012 %.% #Define nuevo data frame
mutate(pobre=ifelse(np=="No pobre",0,1), #Crea variable de pobreza.
Profesional=ifelse(OcupFuerzaTrab==profesionales,1,0), #Crea flag de Profesional.
Tecnico=ifelse(OcupFuerzaTrab==tecnicos,1,0)) %.% #Crea flag de tecnico.
select(FACTOR:ZONA,pobre,Profesional,Tecnico,ipcn) %.% #Selecciona variables de interés.
group_by(SEGMENTO,CUESTIONARIO,HOGAR,ZONA,REGION) %.% #Genera esquema de agrupación.
summarise(Factor=mean(FACTOR),
pobre=mean(pobre),
Profesionales=sum(Profesional),
Tecnicos=sum(Tecnico),
Ingreso=mean(ipcn)) %.%
mutate(id=paste0(SEGMENTO,CUESTIONARIO,HOGAR,ZONA,REGION)) #Genera id único para uso posterior.
#Establecer el diseño muestral
design2<-svydesign(data=df12,id=~SEGMENTO+id,
strata=~REGION+ZONA,pps="brewer",weights=~Factor)
summary(design2)
#Calculando estadísticos de Pobreza por hogar nacionales
#Porcentaje de pobreza
pobremc<- svymean(~pobre,design=design2,deff=TRUE,na.rm=TRUE)
#Media de pobreza
pobremc
#Efecto del diseño
deff(pobremc)
#Intervalo de confianza
confint(pobremc)
#Coeficiente de variación
cv(pobremc)
#Total de pobres
pobretmc<-svytotal(~pobre,design=design2, deff=TRUE,na.rm=TRUE)
pobretmc
#Efecto del diseño
deff(pobretmc)
#Intervalo de confianza
confint(pobretmc)
#Coeficiente de variación
cv(pobretmc)
#Estimación de quantiles(Ingreso per cápita)
ingresoq<- svyquantile(~Ingreso,quantile= seq(0.2,1,0.2),design=design2, deff=TRUE,na.rm=TRUE)
ingresoq
#Cálculo de razón(Profesionales/Técnicos)
ptratio<- svyratio(~Profesionales, ~Tecnicos, design=design2, deff=TRUE,na.rm=TRUE)
ptratio
#Efecto del diseño
deff(ptratio)
#Intervalo de confianza
confint(ptratio)
#Coeficiente de variación
cv(ptratio)
#Estimaciones por estrato(Zona)
pobremZ<-svyby(~pobre, ~ZONA, design2, svymean,deff=TRUE,na.rm=TRUE)
#Media de pobreza por zona
pobremZ
#Efecto del diseño
deff(pobremZ)
#Intervalo de confianza
confint(pobremZ)
#Coeficiente de variación
cv(pobremZ)
#Estimaciones por estrato(Región)
pobremR<-svyby(~pobre,~REGION, design2, svymean,deff=TRUE,na.rm=TRUE)
#Media de pobreza por zona
pobremR
#Efecto del diseño
deff(pobremR)
#Intervalo de confianza
confint(pobremR)
#Coeficiente de variación
cv(pobremR)
#Estimaciones combinadas
pobremZR<-svyby(~pobre,~REGION+ZONA, design2, svymean,deff=TRUE,na.rm=TRUE)
```
```{r EJ 6.3.2,message=FALSE,results='asis',echo=FALSE}
#Pasando a porcentajes:
pobremZR<- mutate(pobremZR,pobre=pobre*100,
se=se*100)
#Generar en formato tabla resultado de estimaciones de pobreza por estratos
colnames(pobremZR)<-c("Región","Zona","% Pobreza","SE","DEFF")
library(stargazer)
stargazer(pobremZR, type="html",summary=FALSE,
title = "Costa Rica:Estimaciones de pobreza por estrato",
notes = "Fuente:ENAHO 2012,INEC",
digits=2,header=FALSE,
rownames=FALSE)
```
#### Comparativa de las estimaciones publicadas y estimadas en el ejercicio
Para comparar la calidad de las estimaciones, se realizará una comparación entre la medición puntual de % de hogares pobres por Región.[Acá(página 68 del documento)](https://www.dropbox.com/s/psqdvbt8r4nwcja/Resultados%20Generales%20ENAHO-2012.pdf?dl=0) se encuentra el resultado oficial.
```{r EJ 6.4,message=FALSE,echo=FALSE,fig.align='center',fig.height=12,fig.width=16,dev='png'}
#Generando resultados oficiales
pobreoR<- data.frame(REGION=pobremR[,1],pobre=c(16.3,34.5,26.6,34.6,26.2,24.6),
se=c(0.7,1.9,2.1,1.8,1.6,2.0))
pobreoR<- mutate(pobreoR,Estimacion="INEC")
#Generar data frame para gráfico
pobremR<- select(pobremR,REGION,pobre,se) %.%
mutate(Estimacion="Ejercicio",se=se*100,pobre=pobre*100)
pobre<- rbind(pobreoR,pobremR)
pobre$Estimacion<- factor(pobre$Estimacion,c("INEC","Ejercicio"))
library(tidyr)
pobre<- gather(pobre,Indicador,Pobreza,-REGION,-Estimacion,-se)
#Generación de gráfico de comparación
library(ggplot2)
#parametros del plot
breaks<- round(seq(min(pobre$Pobreza)-1,max(pobre$Pobreza)+1,length.out =10),0)
pobre<- mutate(pobre,labels=ifelse(Estimacion=="Ejercicio",as.character(REGION),""))
pobreplot<- ggplot(pobre, aes(x=Estimacion,
y=Pobreza,
group=REGION,
fill=REGION))+
geom_point(aes(fill=REGION,
colour=REGION,
size=se),shape=21)+
geom_line()+
geom_text(aes(label=labels),size=4,hjust=-0.4)+
scale_size_continuous(name="Error\nEstándar",range = c(5,20))+
scale_y_continuous(breaks=breaks)+
scale_fill_discrete(guide=FALSE)+
scale_colour_discrete(guide=FALSE)+
theme_minimal()+
labs(x = "Estimación",y = "% Pobreza")+
ggtitle(expression(atop("Costa Rica:Comparativa de las estimaciones de Pobreza por Región",atop(italic("Según Estimación oficial y estimación del ejercicio"), ""))))+
theme(axis.text.x = element_text(hjust=0, vjust=1),
plot.title = element_text(size = 18, face = "bold", colour = "black", vjust = -1),
strip.text.x = element_text(size=14,face="bold"),
strip.text.y = element_text(size=11),
strip.background = element_rect(colour="gray11", fill="gray87"))
pobreplot
```
## Resumen de las funciones más relevantes utilizadas
Paquete|Tipo |Función
------ |----- | -------------
Base |Selección de muestra| `sample(x=data, size=n, replace = FALSE, prob = NULL)`
dplyr |Selección de muestra| `sample_n(tbl=dataframe, size=n, replace = FALSE, weight = NULL, .env = parent.frame())`
SamplingUtil |Selección de muestra(sistemática)| `sys.sample(N=Total, n=muestra)`
SamplingUtil |Tamaño de muestra|`nsize(x=data, r = error_relativo, abs = error_absoluto, alpha = 0.05)`
SamplingUtil |Tamaño de muestra(Estratificada)|`nstrata(n=tamaño muestra, wh=vector pesos, sh = vector desviaciones, ch = vector de costos, method = c("proportional","optimal", "neyman")`
DescTools |Intervalos de Confianza|`MeanCI(variable=df$variable,conf.level = 0.95, na.rm = FALSE)`
pps |Selección PPT sistemática|`ppssstrat(UPMs$Mta,UPMs$Estrato,asize=Tamaño muestra por Estrato)`
survey |Configuración de diseño complejo | `svydesign(data=dataframe,id=~ID_Etapa_1+...+ID_Etapa i,strata=~Estrato_1+...+Estrato_n,pps="brewer",prob=~fa+...+fk)+weights=Factor Expansión`
survey |Estimación compleja(media)|`svymean(~variable,diseño,deff=TRUE,na.rm=TRUE)`
survey |Estimación compleja(estratos)|`svyby(~variable,~Estrato 1+...+Estrato_n,diseño,c(svymean,svyratio,svytotal),deff=TRUE,na.rm=TRUE)`
survey |Estimación compleja(cuantiles)|`svyquantile(~variable,quantile= vector de valores,diseño, deff=TRUE,na.rm=TRUE)`
survey |Estimación compleja(razones)|`svyratio(~denominador,~numerador,diseño, deff=TRUE,na.rm=TRUE)`
survey |Estimación compleja(totales)|`svytotal(~variable,diseño, deff=TRUE,na.rm=TRUE)`
survey |Estimación compleja(Intervalo)|`confint(Objeto de svymean,svyratio,svytotal)`
survey |Estimación compleja(Coeficiente de variación)|`cv(Objeto de svymean,svyratio,svytotal)`
survey |Estimación compleja(Efecto del diseño)|`deff(Objeto de svymean,svyratio,svytotal)`
## Repositorio del tutorial
[Acá](https://github.com/DFJL/Complex_Sampling_R) se encuentra el código para reproducir todos los ejercicios de este tutorial.
## Sesión de R
```{r session}
sessionInfo()
```
## Referencias
```{r Ref,echo=FALSE,message=FALSE,results="asis",warning=FALSE}
library(knitcitations)
survey <- citep("10.1002/9780470580066")
#MIA<- citep("http://www.virtual.unal.edu.co/cursos/sedes/manizales/4030006/lecciones/capituloseis/6_5.html")
#ENAHO12<-citep("http://www.inec.go.cr/anda4/index.php/catalog/130")
#ENAHO13<-citep("http://www.inec.go.cr/anda4/index.php/catalog/137")
bibliography()
```