library(lme4)
library(multcomp)
library(lattice)
source(file.path(pfadu, "phoc.txt"))

sz = read.table(file.path(pfadu, "sz.txt"))
head(sz)
tab = with(sz, table(Dialekt, Frikativ))
prop = prop.table(tab, 1)
# Abbildung: Häufigkeiten
barchart(tab, auto.key=T, horizontal=F, ylab = "Häufigkeit")
# Proportionen
barchart(prop, auto.key=T, horizontal=F, ylab="Proportion")

# Test
o = glm(Frikativ ~ Dialekt, family=binomial, data = sz)
anova(o, test="Chisq")
# das gleiche:
ohne = glm(Frikativ ~ 1, family=binomial, data = sz)
# oder
ohne = update(o, ~. -Dialekt)
anova(ohne, o, test="Chisq")
# Dialekt hat einen signifikanten Einfluss auf die s/z Verteilung (c^2[1] = 5.3, p < 0.05)

# Beispiel 2
coronal = read.table(file.path(pfadu, "coronal.txt"))
tab  = with(coronal, table(Socialclass, Fr))
prop  = prop.table(tab, 1)
barchart(prop, auto.key=T, horizontal=F, ylab="Proportion")
o = glm(Fr ~ Socialclass, family = binomial, data = coronal)
anova(o, test="Chisq")
summary(glht(o, linfct=mcp(Socialclass="Tukey")))

# Beispiel 3
ovokal = read.table(file.path(pfadu, "ovokal.txt"))
tab = with(ovokal, table(Jahr, Vokal))
barchart(tab, auto.key=T, horizontal=F)
# oder
prop = prop.table(tab, 1)
barchart(prop, auto.key=T, horizontal=F)

o = glm(Vokal ~ Jahr, family=binomial, data = ovokal)
anova(o, test="Chisq")

# Mit random factor
pr = read.table(file.path(pfadu, "preasp.txt"))
# Ein Sprecher produzierte oft /e, o, a/: diese Variabilität
# soll herausgeklammert werden
with(pr, table(spk, vtype, Pre))

tab = with(pr, table(vtype, Pre))
prop = prop.table(tab, 1)
barchart(prop, auto.key=T, horizontal=F, ylab = "Proportion")

o = lmer(Pre ~ vtype + (1|spk), family=binomial, data = pr)
ohne = update(o, ~ . - vtype)
anova(o, ohne)
summary(glht(o, linfct=mcp(vtype="Tukey")))

# Beispiel 5
# Mit random factor und 2 fixed (unabhängige) Faktoren
tab = with(pr, table(vtype, ptonic, Pre))
prop = prop.table(tab, 1:2)
barchart(prop, auto.key=T, horizontal = F)

o = lmer(Pre ~ vtype * ptonic + (1|spk), family=binomial, data=pr)
ohne = lmer(Pre ~ vtype + ptonic + (1|spk), family=binomial, data=pr)
anova(o, ohne)
plabs = with(pr, interaction(vtype, ptonic))
beide = lmer(Pre ~ plabs + (1|spk), family=binomial, data=pr)
p = summary(glht(beide, linfct=mcp(plabs = "Tukey")))
round(phsel(p), 3)
round(phsel(p, 2), 3)


