rm(list = ls(all = TRUE)) #clear workspace

## C O D E B O O K
library(memisc)
data <- spss.system.file("231016_ENCUESTA_CDMX.sav")
Write(codebook(data), file="Codebook.txt")

## E S T I M A C I O N E S
library(survey)
library(foreign)

data <- read.spss("231016_ENCUESTA_CDMX.sav", to.data.frame=TRUE)
design <- svydesign(ids=~con, strata=~est, 
                    weights=~ponde_RAKING, data=data, nest = TRUE)
gen.estimates <- function(x) {
  out <- svymean(make.formula(x), design, deff=TRUE)
  coef <- coef(out)*100
  se <- sqrt(diag(vcov(out)))*100
  ci <- confint(out)*100
  moe <- (ci[,2] - ci[,1])/2
  deff <- deff(out)
  coef.var <- cv(out)
  tmp <- cbind("Punto Estimado"=coef, "Error estandar"=se,
               "Margen de error"=moe, "Intervalo" = ci[,1], "de Confianza"=ci[,2],
               "Deff"=deff, "CV"=coef.var)
  round(tmp, 1)
}
vars <- grep("^p[1-9]|^s[1]|^s[3-9]", names(data), value=T)
out <- lapply(vars, gen.estimates)
names(out) <- attributes(data)$variable.labels[vars]
capture.output(print(out), file = "Estimaciones_e_Intervalos_de_Confianza.txt")
