library(DanielBiostatistics10th)

# Example 13.3.1; Page 673, 
d1331 = c(4, 5, 8, 8, 9, 6, 10, 7, 6, 6)
BSDA::SIGN.test(d1331, md = 5)

# Example 13.3.2; Page 677, 
head(EXA_C13_S03_02)
with(EXA_C13_S03_02, BSDA::SIGN.test(x = X, y = Y, alternative = 'less'))

# Example 13.4.1; Page 683, 
d1341 = c(4.91, 4.10, 6.74, 7.27, 7.42, 7.50, 6.56, 4.64, 5.98, 3.14, 3.23, 5.80, 6.17, 5.39, 5.77)
wilcox.test(d1341, mu = 5.05)

# Example 13.5.1; Page 686, 
head(EXA_C13_S05_01)
(med1351 = median(unlist(EXA_C13_S05_01), na.rm = TRUE)) # common median
addmargins(t1351 <- with(EXA_C13_S05_01, expr = {
  tmp <- cbind(Urban = table(URBAN < med1351), Rural = table(RURAL < med1351, useNA = 'no'))
  rownames(tmp) <- paste('Number of scores', c('above', 'below'), 'median')
  tmp
})) # Table 13.5.2
chisq.test(t1351, correct = FALSE)

# Example 13.6.1; Page 691, 
head(EXA_C13_S06_01)
with(EXA_C13_S06_01, wilcox.test(X, Y, exact = FALSE, alternative = 'less'))

# Example 13.7.1; Page 699, 
head(EXA_C13_S07_01)
ks.test(EXA_C13_S07_01$GLUCOSE, y = pnorm, mean = 80, sd = 6)

# Example 13.8.1; Page 705 (10th ed), Page 611 (11th ed) 
(d1381 = data.frame(Air = c(12.22, 28.44, 28.13, 38.69, 54.91),
                    Benzaldehyde = c(3.68, 4.05, 6.47, 21.12, 3.33),
                    Acetaldehyde = c(54.36, 27.87, 66.81, 46.27, 30.19))) # Table 13.8.1
with(data = reshape2::melt(
  data = d1381, 
  id.vars = NULL, 
  value.name = 'Eosinophil', 
  variable.name = 'Exposure'
), expr = kruskal.test(x = Eosinophil, g = Exposure))

# Example 13.8.2; Page 708 (10th ed), Page 613 (11th ed) 
head(EXA_C13_S08_02)
with(data = reshape2::melt(
  data = EXA_C13_S08_02, 
  id.vars = NULL, 
  value.name = 'Value', 
  variable.name = 'Hospital'
), expr = kruskal.test(x = Value, g = Hospital))

# Example 13.9.1; Page 713 (10th ed); Page 618 (11th ed)
head(EXA_C13_S09_01)
m1391 = as.matrix(EXA_C13_S09_01[LETTERS[1:3]], rownames.force = TRUE)
names(dimnames(m1391)) = c('Therapist', 'Model')
m1391 # Table 13.9.1
friedman.test(m1391)

# Example 13.9.2; Page 715 (10th ed); Page 620 (11th ed) 
head(EXA_C13_S09_02)
m1392 = as.matrix(EXA_C13_S09_02[LETTERS[1:4]], rownames.force = TRUE)
names(dimnames(m1392)) = c('Animal', 'Dose')
m1392 # Table 13.9.2
friedman.test(m1392)

# Example 13.10.1; Page 720, 
head(EXA_C13_S10_01)
with(EXA_C13_S10_01, cor.test(X, Y, method = 'spearman'))

# Example 13.10.2; Page 722, 
head(EXA_C13_S10_02)
with(EXA_C13_S10_02, cor.test(V2, V3, method = 'spearman', exact = FALSE))

# Example 13.11.1-13.11.2; Page 728-729, 
testosterone <- c(230, 175, 315, 290, 275, 150, 360, 425)
citricAcid <- c(421, 278, 618, 482, 465, 105, 550, 750)
robslopes::TheilSen(x = citricAcid, y = testosterone)
# textbook uses *central* median of ordered pairs, while ?robslopes::TheilSen uses *upper* median
summary(mblm::mblm(testosterone ~ citricAcid, repeated = FALSE)) # Figure 13.11.1 (11th ed)

