 ---
title: "Chi-squared"
author: "Tera Letzring"
date: "November 2017"
output: html_document
---

```{r setup, include=FALSE}

knitr::opts_chunk$set(echo = TRUE)
```

```{r read in data}

#set the working directory (wd) to the folder that contains the script file, and read in the data
x <- getwd()
setwd(x)

mydata = read.table("AdelaideSurvey.csv", header=T, sep=",")  
attach(mydata)
head(mydata)
```

```{r goodness of fit - equal expected values}

#frequency of Exercise
table(Exercise)

counts <- c(Frequent=115, None=24, Some=98)

#default output
chisq.test(counts, correct=FALSE)
```

```{r goodness of fit - unequal expected values with p-value from Monte Carlo simulation}

#default ouput
chisq.test(counts, correct=FALSE, p=c(.25, .25, .5), simulate.p.value=TRUE, B=2000)

#specified output
GoodFit <- chisq.test(counts, correct=FALSE, p=c(.25, .25, .5), simulate.p.value=TRUE, B=2000)

GoodFit$statistic  #chi-squared statistic
GoodFit$parameter  # df - will be NA if simulate.p.value is TRUE
GoodFit$p.value    
GoodFit$observed   #observed values
GoodFit$expected   #expected values
GoodFit$residuals  #residuals for each group: (O-E)/sqrt(E)
```

```{r test of association}

#frequencies for table of counts for 2 variables
table(WritingHand, Sex)

counts <- matrix(c(7, 10, 110, 108), byrow=TRUE, nrow=2)

#default output
chisq.test(counts, correct=FALSE)

#Fisher's Exact Test
fisher.test(counts)

#p-value from Monte Carlo simulation
chisq.test(counts, correct=FALSE, simulate.p.value=TRUE, B=1000)

#specified output
TestAssoc <- chisq.test(counts, correct=FALSE, simulate.p.value=TRUE, B=1000)

TestAssoc$statistic  ##chi-squared statistic
TestAssoc$parameter
TestAssoc$p.value
TestAssoc$observed
TestAssoc$expected
TestAssoc$residuals
```


