> # install.packages("MASS")
> library(MASS)     
> 
> print(str(survey))
'data.frame':	237 obs. of  12 variables:
 $ Sex   : Factor w/ 2 levels "Female","Male": 1 2 2 2 2 1 2 1 2 2 ...
 $ Wr.Hnd: num  18.5 19.5 18 18.8 20 18 17.7 17 20 18.5 ...
 $ NW.Hnd: num  18 20.5 13.3 18.9 20 17.7 17.7 17.3 19.5 18.5 ...
 $ W.Hnd : Factor w/ 2 levels "Left","Right": 2 1 2 2 2 2 2 2 2 2 ...
 $ Fold  : Factor w/ 3 levels "L on R","Neither",..: 3 3 1 3 2 1 1 3 3 3 ...
 $ Pulse : int  92 104 87 NA 35 64 83 74 72 90 ...
 $ Clap  : Factor w/ 3 levels "Left","Neither",..: 1 1 2 2 3 3 3 3 3 3 ...
 $ Exer  : Factor w/ 3 levels "Freq","None",..: 3 2 2 2 3 3 1 1 3 3 ...
 $ Smoke : Factor w/ 4 levels "Heavy","Never",..: 2 4 3 2 2 2 2 2 2 2 ...
 $ Height: num  173 178 NA 160 165 ...
 $ M.I   : Factor w/ 2 levels "Imperial","Metric": 2 1 NA 2 2 1 1 2 2 2 ...
 $ Age   : num  18.2 17.6 16.9 20.3 23.7 ...
NULL
> ??MASS::survevy
> 
> wh.clap = data.frame(survey$Clap,survey$W.Hnd)
> wh.clap.tbl = table(survey$Clap,survey$W.Hnd) 
> wh.clap.tbl
         
          Left Right
  Left       9    29
  Neither    5    45
  Right      4   143
> chisq <- chisq.test(wh.clap.tbl)
경고메시지(들): 
chisq.test(wh.clap.tbl)에서:
  카이제곱 approximation은 정확하지 않을수도 있습니다
> chisq

	Pearson's Chi-squared test

data:  wh.clap.tbl
X-squared = 19.252, df = 2, p-value = 6.598e-05

> o <- chisq$observed
> e <- chisq$expected
> o
         
          Left Right
  Left       9    29
  Neither    5    45
  Right      4   143
> round(e, 2)
         
           Left  Right
  Left     2.91  35.09
  Neither  3.83  46.17
  Right   11.26 135.74
> res <- (e-o)/sqrt(e)
> round(res,2)
         
           Left Right
  Left    -3.57  1.03
  Neither -0.60  0.17
  Right    2.16 -0.62
> chisq.cal <- sum(res^2)
> p.val <- pchisq(chisq.cal, df=2, lower.tail = F)
> chisq.cal
[1] 19.25239
> p.val
[1] 6.597765e-05
> chisq

	Pearson's Chi-squared test

data:  wh.clap.tbl
X-squared = 19.252, df = 2, p-value = 6.598e-05

> 
> barplot(wh.clap.tbl, beside = TRUE, 
+         col = c("red", "lightgreen", "blue"),
+         main = "wh vs ex",
+         xlab = "Exercise Level", ylab = "Number of Students")
> 
> legend("center", legend = rownames(wh.clap.tbl), 
+        fill = c("red", "lightgreen" ,"blue"))
>
>