Week 6 figures - Lecture 11

chi-square
qchisq
pchisq
chisq.test
Author
Affiliation
Lecture date

May 6, 2024

Modified

June 13, 2024

1. Math

a. Chi-square test statistic with example

\[ \begin{align} \chi^2 &= \sum\frac{(O - E)^2}{E} \\ &= \frac{55 - 47.2}{47.2} +...+\frac{45-31.9}{31.9} \\ &= 15.276 \end{align} \]

b. expected counts with example

\[ \begin{align} expected &= \frac{row \, total \times column \, total}{table \, total} \\ &= \frac{126 \times 118}{315} \\ &= 47.2 \end{align} \]

c. degrees of freedom

\[ df = (number\;of\;rows - 1) \times (number\;of\;columns - 1) \]

2. Code

a. data

Code
# creating matrix of survey results
survey <- matrix(
  c(55, 38, 33, 41, 25, 29, 22, 27, 45),
  nrow = 3,
  ncol = 3,
  byrow = TRUE,
  dimnames = list(c("walking_distance", "driving_distance", "out_of_town"),
                  c("trails", "dog_access", "wildlife_viewing"))
)

# displaying survey results
survey
                 trails dog_access wildlife_viewing
walking_distance     55         38               33
driving_distance     41         25               29
out_of_town          22         27               45

b. calculating critical value

Code
critical_value <- qchisq(p = 0.05, # probability (area under curve)
                         df = 4, # degrees of freedom
                         lower.tail = FALSE) # calculate boundary where 0.05 is to the right

critical_value
[1] 9.487729

c. calculating p-value

Code
p_value <- pchisq(q = 15.276, # test statistic
       df = 4, # degrees of freedom
       lower.tail = FALSE) # calculate probability (area under the curve) to the RIGHT of the test statistic

p_value
[1] 0.004161711

d. using chisq.test() function

Code
chisq.test(survey)

    Pearson's Chi-squared test

data:  survey
X-squared = 15.276, df = 4, p-value = 0.004162

Citation

BibTeX citation:
@online{bui2024,
  author = {Bui, An},
  title = {Week 6 Figures - {Lecture} 11},
  date = {2024-05-06},
  url = {https://spring-2024.envs-193ds.com/lecture/lecture_week-06.html},
  langid = {en}
}
For attribution, please cite this work as:
Bui, An. 2024. “Week 6 Figures - Lecture 11.” May 6, 2024. https://spring-2024.envs-193ds.com/lecture/lecture_week-06.html.