Exercise 1

data(UCBAdmissions) 
UCB <- UCBAdmissions # save typing ftable(UCB)
sum(UCB)
## [1] 4526
#total applicants for each dept
margin.table(UCB, 3) 
## Dept
##   A   B   C   D   E   F 
## 933 585 918 792 584 714
apply(UCBAdmissions, 3, sum)
##   A   B   C   D   E   F 
## 933 585 918 792 584 714
#proportion admited for each dept
tab1 <- margin.table(UCB , c(1,3)) 
tab1 
##           Dept
## Admit        A   B   C   D   E   F
##   Admitted 601 370 322 269 147  46
##   Rejected 332 215 596 523 437 668
tab1[1,] / margin.table(UCB, 3) 
## Dept
##          A          B          C          D          E          F 
## 0.64415863 0.63247863 0.35076253 0.33964646 0.25171233 0.06442577
# or, using prop.table prop.table(margin.table(UCB, c(1, 3)),2)

#proportion in each cell admitted
admit <- UCB[1,,] 
reject <- UCB[2,,]
admit / (admit+reject)
##         Dept
## Gender            A          B          C          D          E          F
##   Male   0.62060606 0.63035714 0.36923077 0.33093525 0.27748691 0.05898123
##   Female 0.82407407 0.68000000 0.34064081 0.34933333 0.23918575 0.07038123

Exercise 2

##      Away
## Home    0   1   2   3   4 Sum
##   0    27  29  10   8   2  76
##   1    59  53  14  12   4 142
##   2    28  32  14  12   4  90
##   3    19  14   7   4   1  45
##   4     7   8  10   2   0  27
##   Sum 140 136  55  38  11 380
## Home
##          0          1          2          3          4 
## 0.20000000 0.37368421 0.23684211 0.11842105 0.07105263
## Away
##          0          1          2          3          4 
## 0.36842105 0.35789474 0.14473684 0.10000000 0.02894737
## Loading required package: grid
## 
## Observed and fitted values for poisson distribution
## with parameters estimated by `ML' 
## 
##  count observed    fitted pearson residual
##      0       76  85.91248       -1.0694349
##      1      142 127.73830        1.2618589
##      2       90  94.96334       -0.5093262
##      3       45  47.06516       -0.3010265
##      4       27  17.49462        0.5432891
## 
## Observed and fitted values for poisson distribution
## with parameters estimated by `ML' 
## 
##  count observed     fitted pearson residual
##      0      140 131.238117        0.7648345
##      1      136 139.526840       -0.2985774
##      2       55  74.169531       -2.2258645
##      3       38  26.284641        2.2850967
##      4       11   6.986181        0.7488822

## 
##  Pearson's Chi-squared test
## 
## data:  tab
## X-squared = 34.868, df = 4, p-value = 4.945e-07

## [1] 1.486842
## [1] 1.063158
##       Home            Away      
##  Min.   :0.000   Min.   :0.000  
##  1st Qu.:1.000   1st Qu.:0.000  
##  Median :1.000   Median :1.000  
##  Mean   :1.487   Mean   :1.063  
##  3rd Qu.:2.000   3rd Qu.:2.000  
##  Max.   :4.000   Max.   :4.000

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.