# Tabla de contingencia tridimensonal
# ACT x EST X SEX con los datos del archivo Actitud.rda

# Para ejecutar el script en R o RStudio es necesario instalar el paquete Deducer
# También el paquete vcd
install.packages("vcd")
library(vcd)

# Tabla ACT x EST X SEX con las frecuencias 
ACT3<-contingency.tables(row.vars=d(ACT),col.vars=d(EST),stratum.var=SEX,data=actitud)
print(ACT3,prop.r=F,prop.c=F,prop.t=F)

# Tablas ACT x EST y ACT x SEX 
ACT1<-contingency.tables(row.vars=d(ACT),col.vars=d(EST,SEX),data=actitud)
ACT1<-add.chi.squared(ACT1)
print(ACT1,prop.r=T,prop.c=T,prop.t=F,expected.n=T,adj.residuals=T)
ggplot() + geom_bar(aes(y = ..count..,x = EST,fill = ACT),data=actitud,position = position_fill())
ggplot() + geom_bar(aes(y = ..count..,x = SEX,fill = ACT),data=actitud,position = position_fill())
assocstats(table(actitud$ACT, actitud$EST))
assocstats(table(actitud$ACT, actitud$SEX))

# Tabla EST x SEX 
ACT2<-contingency.tables(row.vars=d(EST),col.vars=d(SEX),data=actitud)
ACT2<-add.chi.squared(ACT2)
print(ACT2,prop.r=T,prop.c=T,prop.t=F,expected.n=T,adj.residuals=T)
ggplot() + geom_bar(aes(y = ..count..,x = SEX,fill = EST),data=actitud,position = position_fill())
assocstats(table(actitud$EST, actitud$SEX))

# Tabla ACT x EST x SEX 
ACT3<-add.chi.squared(ACT3)
print(ACT3,prop.r=T,prop.c=T,prop.t=F,expected.n=T,adj.residuals=T)
ggplot() + geom_bar(aes(y = ..count..,x = EST,fill = ACT),data=actitud,position = position_fill()) +
  facet_wrap(facets = ~SEX) + ggtitle(label = 'SEX')
summary(subset(actitud,subset=SEX=="Varón"))
SEX1=subset(actitud,subset=SEX=="Varón")
assocstats(table(SEX1$ACT, SEX1$EST))
summary(subset(actitud,subset=SEX=="Mujer"))
SEX2=subset(actitud,subset=SEX=="Mujer")
assocstats(table(SEX2$ACT, SEX2$EST))


# Obtención solamente de la V de Cramer de todas las tablas
assocstats(table(actitud$ACT, actitud$EST))
assocstats(table(actitud$ACT, actitud$SEX))
assocstats(table(actitud$EST, actitud$SEX))
SEX1=subset(actitud,subset=SEX=="Varón")
assocstats(table(SEX1$ACT, SEX1$EST))
SEX2=subset(actitud,subset=SEX=="Mujer")
assocstats(table(SEX2$ACT, SEX2$EST))


# Generación del Data frame a partir de las frecuencias
Actitud = data.frame(
  ACT=factor(rep(1:2, c(513,930)), labels=c("Acuerdo","Desacuerdo")),
  EST=factor(c(rep(1:3, c(158,283,72)), rep(1:3, c(85,479,366))), labels=c("Primarios","Secundarios","Superiores")),
  SEX=factor(c(rep(1:2, c(72,86)), rep(1:2, c(110,173)), rep(1:2, c(44,28)), 
               rep(1:2, c(47,38)), rep(1:2, c(196,283)), rep(1:2, c(179,187))), labels=c("Varón","Mujer")) )
edit(actitud)
save(actitud,file='D:/Datos/Actitud.rda')
