---
title: "Intro R Functions for Statistics"
author: "Ms-RAZ"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## 1.3-3 Variables and Measurement

```{r}
############################
######## CLASS #############
############################

# Load in the data, here we are reading in a .csv file
spotify_top50 <- read.csv("spotify_top50.csv")

View(spotify_top50)

# To check what type of data a particular column is you can use the "class()" function in R
class(spotify_top50$Genre)

# R is treating the Genre as a character... But we want this to be a factor, 
# because music Genre is a type of category
# We can reassign the class by using the function "factor()"
spotify_top50$Genre <- factor(spotify_top50$Genre)

# We can check to make sure it worked with the class() function again, 
# now R is treating it as a Factor with 21 different categories
class(spotify_top50$Genre)
```

## 2.1-3 Describing Data
 
```{r}
#############################
##### MEAN AND MEDIAN #######
#############################
#### HISTOGRAM & BOXPLOT ####
#############################

# Data from 20 women asking their height
height <- c(69, 63, 54, 61, 68, 61, 62, 56, 64, 66, 60, 61, 73, 63, 65, 72, 70, 59, 76, 59)

# Using the R function "mean()" we can quickly calculate the mean whic is 64.1 inches
mean(height) 

# Using the R function "median()" we can quickly calculate the median whic is 63 inches
median(height) 

# Here you can make a quick histogram 
hist(height)

# And here a quick boxplot
boxplot(height)
```

## 2.2-3 Variation  

```{r}
############################
######## VARIATION #########
############################

######## POPULATION DATA ########
quiz_grades <- c(8, 7, 5, 6, 10, 9, 7, 9, 8, 11)

mean(quiz_grades) # mean = 8

# to get the variance of a population, we need to do some tweeking
# R's default is to calculate variance for a SAMPLE

# first we need to know how many observations there are, we can use the "length()" function
# which tells us how long an object is, i.e. how many row (how many observations)
n <- length(quiz_grades) # 10 observations saved as object "n"

# we can use the "var()" function to get the variance for a sample, 
# but to get variance for a population, we need to multiple by ((n-1)/n)
var(quiz_grades) * ((n-1)/n) # variance = 3

# to get the standard deviation, we can just take the squareroot of 3
sqrt(3) # standard deviation = 1.73


######## SAMPLE DATA ########

# R makes this much easier...

var(quiz_grades) # variance = 3.33...
sd(quiz_grades) #standard deivation = 1.83
```

## 3.1-2 Standardization z-score
```{r}
################################
########## z-scores  ###########
################################

##### Z's Exam z-score #####
person_Z <- 45
pop_mean_Z <- 40
sd_Z <- 5

z_score_Z <- (person_Z - pop_mean_Z)/sd_Z

##### D's Exam z-score #####
person_D <- 50
pop_mean_D <- 55
sd_D <- 5

z_score_D <- (person_D - pop_mean_D)/sd_D

z_score_Z
z_score_D

################################
### z-scores & Probability  ####
################################

# Calculate a z-score

SAT_mean <- 1000
SAT_sd <- 210
SAT_score <- 1555

SAT_Z_score <- (SAT_score - SAT_mean)/SAT_sd

# The function "pnorn()" can give you the proprotion (i.e the probability, 
# the "p" in "pnorm") from a normal distribution (the "norm" in "pnorm").
# You need to tell R the z-score (q), the mean, the sd, and the final
# argument you need to give it is where or not to include the tail. 
# 
# You can tell lower.tail = FALSE, which is the equivelent of asking R the proportion of
# people that score ABOVE that z-score, P (z < 2.64)
# 
# If you have a 1555 on the SAT, less tha 0.04% of people scored higher than you
pnorm(q = 1555, mean=1000, sd=210, lower.tail=FALSE)
pnorm(SAT_Z_score, SAT_mean, SAT_sd, lower.tail = FALSE)

# You can tell lower.tail = TRUE, which is the equivelent of asking R the proportion of
# people that score BELOW that z-score, this is like a percentile, P (z > 2.64)
# 
# If you have a 1555 on the SAT, you are in the 99.6th percentile,
# You scored bettr than 99.6% of people
pnorm(q = 1555, mean=1000, sd=210, lower.tail=TRUE)
pnorm(SAT_Z_score, SAT_mean, SAT_sd, lower.tail = TRUE)

# If you want to know how many people fall between two z-scores, 
# (symmetrical z-scores, meaning -1.96 to +1.96), P (-1.96 < z < 1.96)
1-pnorm(q = 1.96, mean=0, sd=1, lower.tail=FALSE)*2

```

## 3.2-2 Probability, z-scores, and z-test

```{r}
################################
##### z-test & Probability  ####
################################

sample_mean <- 68
pop_mean <- 65
sd <- 3.5
n <- 5
    
z_stat <- (sample_mean - pop_mean)/(sd/sqrt(n)) 

# When asking for the probability of seeing a sample_mean GREATER than a certain value, 
# P(sample_mean > 68), P(z > 1.92)
pnorm(z_stat, lower.tail = F) #0.03

# When asking for the probability of seeing a sample_mean LESS than a certain value, 
# P(sample_mean < 68), P(z < 1.92)
pnorm(z_stat, lower.tail = T) #0.97

# When asking for the probability of seeing a sample_mean BETWEEN two symmetric values, 
# P(-1.92 < z < 1.92)
1 - pnorm(z_stat, lower.tail = F)*2 #0.94

################################
##### z-score, z-test, #########
#####  & Probability  ##########
################################
########## Flint, MI ###########
################################

#####  One water sample: z-score ##### 

water_mean <- 2.8
water_sd <- 1.5
water_sample <- 5

water_Z_score <- (water_sample - water_mean)/water_sd

# When asking for the probability of seeing a sample GREATER than a certain value, 
# P( one sample > 5.0), P(z > 1.47)
pnorm(water_Z_score, lower.tail = F) #0.07

##### A sample average: z-test ##### 

sample_water_mean <- 5
water_mean <- 2.8
water_sd <- 1.5
n <- 101
    
z_stat_water_sample <- (sample_water_mean - water_mean)/(water_sd/sqrt(n)) 

# When asking for the probability of seeing a sample_mean GREATER than a certain value, 
# P(sample_mean > 5.0), P(z > 14.74)
pnorm(z_stat_water_sample, lower.tail = F) #0.000000
```

## 5.2-3 Confidence Interval Calculations and Relations
```{r}
############################################
### Confidence Intervals for Known Sigma ###
############################################

average <- 81
sd <- 8
n <- 9

# Critical values depends on level of confidence
# The most common are 95% and 99%, choose the appropriate one

critical_z_95 <- 1.96 #for 95% CI
critical_z_99 <- 2.58 #for 99% CI

# Calculate the Margin of Error
moe <- critical_z_95 * sd/sqrt(n)

# Subtract the Margin of Error to the mean to get the lower bound
# Add the Margin of Error to the mean to get the upper bound

lower_bound <- average - moe
upper_bound <- average + moe
```

## 5.3-3 t-distribution
```{r}
################################
##### Critical t-values ########
################################

# You can look up the critical t value using the "qt()" function in R
# Gives the critical values based on the confidence level you want and df
# p = probabilities, i.e. the confidence level you want, ex. 95% p = c(.025, .975)

# 95% Confidence Interval is associated with 0.025 and .975 (.975 -.025 = .95)
qt(p = c(.025, .975), df = )

# 99% Confidence Interval is associated with 0.005 and 0.995 (0.995 -.005 = .99)
qt(p = c(.005, .995), df = )

# Example with n = 10
n <- 10
df <- n-1

# Critical t-value associated with 95% Confidence 
qt(p = c(.025, .975), df = df) #critical t is 2.26


############################################
## Confidence Intervals for Unknown Sigma ##
############################################
######### Promotion Example ################
############################################

average <- 6
sd <- 1.3
n <- 25
df <- n -1

# Get the critical t value associated with a certain level of confidence based on df

# 99% Confidence Interval is associated with 0.005 and 0.995 (0.995 -.005 = .99)
critical_t_99 <- qt(p = c(.005, .995), df = df)

# Calculate the Margin of Error
# This will be two numbers, the +MOE and the -MOE
moe <- critical_t_99 * sd/sqrt(n)

# You only have to add the MOE to the average to get back the upper and lower bound
confidence_interval <- average + moe
```

## 6.2-3 Hypothesis Test II
```{r}
################################
###### Critical t Values #######
###### One & Two Tailed ########
################################

###############################################
##### TWO TAILED Tests Critical t-values ######
###############################################

# 95% Critical t-values for 95% Confidence, significance = 0.05
two_tail_crit_t_95 <- qt(p = c(.025, .975), df = )
# 99% Critical t-values for 99% Confidence, significance = 0.01
two_tail_crit_t_99 <- qt(p = c(.005, .995), df = )

##############################################
##### ONE TAILED Tests Critical t-value ######
##############################################

#### RIGHT TAIL TEST ####
# If you are testing the hypothesis something is GREATER than
# 
# 95% Critical t-values for 95% Confidence, significance = 0.05
right_tail_crit_t_95 <- qt(p = .95, df = )
# 99% Critical t-values for 99% Confidence, significance = 0.01
right_tail_crit_t_99 <- qt(p = .99, df = )

#### LEFT TAIL TEST ####
# If you are testing the hypothesis something is LESS than
# 
# 95% Critical t-values for 95% Confidence, significance = 0.05
left_tail_crit_t_95 <- qt(p = .05, df = )
# 99% Critical t-values for 99% Confidence, significance = 0.01
left_tail_crit_t_99 <- qt(p = .01, df = )
```

## 6.2-3 Hypothesis Test II
```{r}
################################
########### t-tests ############
###### One & Two Tailed ########
####### w/ Summary Data ########
################################

#########################################
##### t-test One sample, RIGHT Tail #####
#########################################

# First fill in the information that is know: Emergency Room Wait Time

sample_mean <- 13
pop_mean <- 10
sd <- 1.3
n <- 20
df <- n-1

# Find the critical values: 95% Critical t-values for 95% Confidence, significance = 0.05
right_tail_crit_t_95 <- qt(p = .95, df = df) # critical t = 1.729

# Calculate the t-statistic
t_stat_one_sample <- (sample_mean - pop_mean)/(sd/sqrt(n)) # t-statistic = 10.32

# Our t-statistic (10.32) is greater than the critcal t value (1.729)
# We can reject the null hypothesis. 

#########################################
##### t-test One sample, LEFT Tail #####
#########################################

# First fill in the information that is know: Football and Self-Esteem

sample_mean <- 39
pop_mean <- 40
sd <- 6.9
n <- 25
df <- n-1

# Find the critical values: 95% Critical t-values for 95% Confidence, significance = 0.05
left_tail_crit_t_95 <- qt(p = .05, df = df) # critical t = -1.71

# Calculate the t-statistic
t_stat_one_sample <- (sample_mean - pop_mean)/(sd/sqrt(n)) # t-statistic = -0.72

# Our t-statistic (-0.72) is not LESS than the critcal t value (-1.71)
# We FAIL reject the null hypothesis. 


#########################################
##### t-test One sample, TWO Tailed #####
#########################################

# First fill in the information that is know: Behavior Modification and Sodas

sample_mean <- 4
pop_mean <- 8
sd <- 2.5
n <- 12
df <- n-1

# Find the critical values: 95% Critical t-values for 95% Confidence, significance = 0.05
two_tail_crit_t_95 <- qt(p = c(.025, .975), df = df) # critical ts = -2.20, 2.20

# Calculate the t-statistic
t_stat_one_sample <- (sample_mean - pop_mean)/(sd/sqrt(n)) # t-statistic = -5.54

# Our t-statistic (-5.54) is further out than the critcal t values (-2.20, 2.20)
# We reject the null hypothesis.
```

6.2-3 Hypothesis Testing II
```{r}
#########################################
##### t-test One sample, TWO Tailed #####
############### p-values ################
#########################################

# With R, we can also look up the exact p-value using "pt()"
# The "p" in "pt()" is asking for the p value from a t distribution
# the "q" in "pt()" is asking you to put in the t-statistic you calculated above
# We also need to use the "abs()" function to take the absolute value of the t-statistic, 
# then add a "-" sign in front... I know it's strange but it works!

# Example of a RIGHT Tail t-test 
# Emergency Room Wait Time: t-statistic (10.32), df = 19
# p = 0.00000
pt(q = -abs(10.32), df = 19) 

# Example of a LEFT Tail t-test 
# Football and Self-Esteem: t-statistic (-0.72), df = 24
# p = 0.24
pt(q = -abs(-0.72), df = 24) 

# Example of a TWO Tail t-test 
# Behavior Modification and Sodas: t-statistic (-5.54), df = 11
# p = 0.0001
pt(q = -abs(-5.54), df = 11, lower.tail = T)*2 
```

## 7.1-4 One Sample t-test
```{r}
#########################################
##### t-test One sample, TWO Tailed #####
#########################################

# First fill in the information that is know: Freshman 15

sample_mean <- 13
pop_mean <- 15
sd <- 4
n <- 25
df <- n-1

# Find the critical values: 95% Critical t-values for 95% Confidence, significance = 0.05
two_tail_crit_t_95 <- qt(p = c(.025, .975), df = df) # critical ts = -2.064, 2.2064

# Calculate the t-statistic
t_stat_one_sample <- (sample_mean - pop_mean)/(sd/sqrt(n)) # t-statistic = -2.5

# Our t-statistic (-2.5) is further out than the critcal t values (-2.064, 2.2064)
# We reject the null hypothesis.

############################################
#### Confidence Intervals for One Sample ###
############## t -test #####################
############################################

# Calculate the Margin of Error
# This will be two numbers, the +MOE and the -MOE
moe <- two_tail_crit_t_95 * sd/sqrt(n)

# You only have to add the MOE to the average to get back the upper and lower bound
confidence_interval <- sample_mean + moe

# The 95% CI [11.35, 14.65]
```

## 7.1-4 One Sample t-test
```{r}
# This is how to do a One-Sample t-test with data (rather than summary statistics)

# R has some datasets included, we can use the "InsectSprays" data set for the example
data <- InsectSprays

# R will automatically calculate the means number of bug bites when you put "data" in
# Then you tell R what the population mean you are testing against is
# Let's say the average number of bug bites for someone not wear any bug spray is mu = 14
# We want to do a two-tailed test to see if there is any difference wear bug spray

t.test(x = data$count, mu = 14, alternative = "two.sided")

# We could also run a one-tailed test, either left or right, by specifying 
# alternative = "less" or alternative = "greater" respectively 
# Here is would make more sense to do a left sided, LESS than, test bc it looks 
# like people who wear bug spray get less bug bites

t.test(x = data$count, mu = 14, alternative = "less")

# Both of these tests were significant. R also gives you the t-statistic, degrees of freedom, 
# a p-value, a confidence interval, and the mean difference between the sample and mu
```

## 7.2-4 Effect Size Cohen's d
```{r}
sample_mean <- 13
pop_mean <- 15
sd <- 4

cohens_d <- (sample_mean - pop_mean)/sd 
```

##7.3-4 Independent Samples t-tests
```{r}
#########################################
##### t-test Independent Samples ######## 
############# TWO Tailed ################
#########################################

# First fill in all of the information

sample_mean_1 <- 8.2
sample_mean_2 <- 5.3
sd_1 <- 2.1
sd_2 <- 3.2
n_group_1 <- 8
n_group_2 <- 14
df_group_1 <- n_group_1-1
df_group_2 <- n_group_2-1
N <- n_group_1 + n_group_2
df_independent <- N-2

# Calculate the Pooled Standard Deviation
pooled_sd <- sqrt( ( (df_group_1*sd_1^2) + (df_group_2*sd_2^2) ) / df_independent)
# Calculate the Pooled Standard Error
pooled_se <- sqrt((sd_1^2/n_group_1) + (sd_2^2/n_group_2))

#Find the critical values
two_tail_crit_t_95 <- qt(p = c(.025, .975), df = df_independent) # critical ts = -2.064, 2.2064

# Calculate the test statistic
t_stat_independent <- (sample_mean_1 - sample_mean_2)/(pooled_se)

# Confidence Interval
moe <- two_tail_crit_t_95 * pooled_se
confidence_interval <- (sample_mean_1 - sample_mean_2) + moe  # [0.54, 5.26]
```

## 7.3-4 Independent Samples t-tests
```{r}
#########################################
##### t-test Independent Samples ######## 
############## w/ Data ##################
#########################################

# Read in some data
college <- read.csv("college_majors.csv")

# Look at all the majors
table(college$Major_category)

# Load the package "tidyverse" to help us filter the data we want
library(tidyverse)

# Filter the majors of interest: Agriculture & Natural Resources vs. Biology & Life Science
A_N <- filter(college, college$Major_category == "Agriculture & Natural Resources")
Bio <- filter(college, college$Major_category == "Biology & Life Science")

# Load the package "psych" to help us with descriptive statistics
library(psych)
describe(A_N[,4:11])
describe(Bio[,4:11])

t.test(A_N$Median, Bio$Median, var.equal = T)

#Business vs. Biology & Life Science 
biz <- filter(college, college$Major_category == "Business")
describe(biz[,4:11])
describe(Bio[,4:11])

t.test(biz$Median, math$Median)

describe(biz[,4:11])
describe(Bio[,4:11])

t.test(biz$Median, Bio$Median, var.equal = T)
```

## 7.4-4 Dependent Samples t-tests
```{r}
#########################################
####### t-test Dependent Samples ######## 
############# TWO Tailed ################
#########################################

# Using summary data, filling in the information

meand_dif <- -8.9
sd_d <- 8.77
n <- 8
df_dependent <- n -1

# Find the critical value, 99% confidence
two_tail_crit_t_99 <- qt(p = c(.005, .995), df = df_dependent) # t-critical: -3.499, 3.499

# Calculate the test statistic
t_stat_dependent <- meand_dif/(sd_d/sqrt(n)) #t-statistic = -2.87

# Our t-statistic (-2.87) is not further out than the critcal t values (-3.499, 3.499)
# We FAIL to reject the null hypothesis.


# Same question but using data instead of summary staistics

pre <- c(155, 228, 141, 162, 211, 164, 184, 172)
post <- c(154, 207, 147, 157, 196, 150, 170, 165)

t.test(post, pre, paired = T, conf.level = .99) 
# Same result, our t-statistic (-2.87) is not further out than the critcal t values (-3.499, 3.499)
# You can also see the confidence interval contains zero and is this not significant
# Notice the p-value is less than .05 but not less than .01, our level of significance for this example
# We FAIL to reject the null hypothesis.
```
## 7.4-4 Dependent Samples t-tests
```{r}
#########################################
####### t-test Dependent Samples ######## 
############# TWO Tailed ################
############## with Data ################
#########################################

diet_data <- read.csv("dietdataset.csv")

# Looking at the mean and standard deviation of the weights before dieting
mean(diet_data$pre.weight)
sd(diet_data$pre.weight)

# Looking at the mean and standard deviation of the weights after dieting
mean(diet_data$weight6weeks)
sd(diet_data$weight6weeks)

# Conduct the t-test, to do a Dependendent samples, make sure to tell R 
# "paired = TRUE" which let's R know it's a dependent samples test
t.test(diet_data$pre.weight, diet_data$weight6weeks, paired = TRUE)
```

## 8.2-2 ANOVA II
```{r}
#########################################
########### Critical F-Value ############ 
#########################################

# You can find the critical F-value using the "qf()" function
# df1 is the degrees of freedom Between (groups), k-1
# df2 is the degrees of freedom Within (people) N-k

qf(.95, df1=2, df2=7) 
```

## 8.2-2 ANOVA II
```{r}
library(plyr)

# Loading in the dataset 
bug_spray <- InsectSprays 

# Renaming the groups, you do not have to do this
bug_spray$spray <- revalue(bug_spray$spray, c("A"= "Natural Oils", "B" = "Citronelle Candle", "C" = "DEET", "D"= "Citronelle Spray", "E" = "Picaridin", "F" = "Nothing")) 

# Get some descriptive statistics for the different groups
describeBy(bug_spray, group = "spray") 

# This is the simple ANOVA function "aov()" 
# The first input is the outcome variable, here it is "count" which is the number of bug bites
# The next input is the grouping variable, here is it the different types of bug "spray"
# Lastly, you tell R the name of the dataset
bug_bites_anova <- aov(count ~ spray, data = bug_spray) 

# This gives you all the important summary information, 
# this is also where you will see the F-statistic and signficance
summary(bug_bites_anova) 

# Since our F-statistic was significant, we can look at the pairwise comparisons using "TuskeyHSD()" function
TukeyHSD(bug_bites_anova) 
```

## 9.1-2 Correlation
```{r}
# The data
hours <- c(0,2,3,4,5)
questions <- c(2,3,6,9,10)

# Correlations are quick with "cor()"
cor(hours, questions)

# We can also quickly look at a scatterplot
plot(hours, questions)

# Lastly, we can test the statistical significance of a correlation
# The null hypothesis is that the correlation is zero
cor.test(hours, questions)
```

## 9.1-2 Correlation
```{r}
# Read in the data
spotify_2000 <- read.csv("spotify_2000.csv")

# Sometimes R will misinterpret the class of a variable, so we reassign it
# R read the Duration of the song as a factor (categorical variable) rather than a number
# So we use the function "as.numeric" to change it
spotify_2000$Duration <- as.numeric(spotify_2000$Duration)

# We can easily get the correlation for two numeric variable using "cor()"
cor(spotify_2000$Energy, spotify_2000$Loudness_dB) # r = 0.74

# We can plot the data 
plot(spotify_2000$Energy, spotify_2000$Loudness_dB,
     main = "Scatterplot of Loudness and Energy",
     xlab = "Energy",
     ylab = "Loudness")

# If we don't now which variable might correlate, we can use the correlation function 
# on the numeric data to create a correlation matrix
spotify_corrs <- cor(spotify_2000[, 5:14])

# The code below just makes the correlation matrix prettier
# The "round()" function will round the values to a specified digit, here it's 2
spotify_corrs <- round(spotify_corrs, 2) 

# The rest of this code remove the upper half of the matrix because it is just a repeat of what is on the bottom
# You do not have to do this, it just makes it prettier
upper <- spotify_corrs
upper[upper.tri(spotify_corrs)] <- ""
upper <- as.data.frame(upper)
```

## 9.2-2 Regression
```{r}
#########################################
####### Simple Linear Regression ######## 
#########################################

# The data
hours <- c(0,2,3,4,5)
questions <- c(2,3,6,9,10)

# To run a simple linear regression in R, use the "lm()" function
regression_model <- lm(questions ~ hours)

# Then look at the output from the regression using the "summary()" function
summary(regression_model)
```

## 9.2-2 Regression
```{r}
#########################################
###### Multiple Linear Regression #######
#########################################

# The data
admissions <- read.csv("admission_predict.csv")

# Look at the variables
names(admissions)

# To run a simple linear regression in R, use the "lm()" function
admissions_model <- lm(ChanceofAdmit ~ GREScore + SOP + LOR + GPA + Research, data = admissions)

# Then look at the output from the regression using the "summary()" function
summary(admissions_model)
```

## 10.2-3 Chi-Squared Test of Independence
```{r}
#########################################
############# Chi-Squared ###############
######## Test of Independence ###########
#########################################

# The data. Using data from our Contingency Tables PPT 
# This is one way to unput the data if you are working with summary statistics. 
happiness_income <- as.table(rbind(c(104, 314, 119), c(83, 494, 277), c(29, 178, 135)))
dimnames(happiness_income) <- list(Class = c("Lower", "Middle", "Upper"),
                    Happiness = c("Unhappy","Neutral", "Happy"))

chisq.test(happiness_income)

# Titanic Survival and Class. 
titanic <- as.table(rbind(c(203, 118, 178, 212), c(122, 167, 528, 673)))
dimnames(titanic) <- list(Status = c("Survived", "Died"),
                    Class = c("First","Second", "Third", "Crew"))

chisq.test(titanic)  

# The data. Using data from our Contingency Tables PPT
# Test Grade and Studying

study_grades <- as.table(rbind(c(11, 17, 7, 3), c(1, 4, 12, 15)))
dimnames(study_grades) <- list(Status = c("Studied", "Didn't Study"),
                    Letter_Grade = c("A","B", "C", "D"))

chisq.test(study_grades)
```

## 10.3-3 Chi-Squared Test of Goodness of Fit 
```{r}
#########################################
############# Chi-Squared ###############
######## Goodness of Fit Test ###########
#########################################

# Movie Genres
movie_genre <- as.table(rbind(c(32, 24, 35, 29)))
dimnames(movie_genre) <- list(Status = c("Action", "Comedy", "Romance", "Horror"))

chisq.test(movie_genre)

# UT vs USA Racial-Ethnic Demographics (UNEQUAL proportions)
ut <- as.table(rbind(c(41, 4, 21, 19, 15)))
dimnames(ut) <- list(Status = c("White", "Black", "Latinx", "Asian", "Other"))

# Because we have an expected pattern for race-ethnicity in the USA, we need to tell R
# what those proportions are
expected_proportions <- c(.61, .13, .16, .05, .05)

# We then put the UT data and the expected proportions into the "chisq.test()" function  
chisq.test(ut, p = expected_proportions)

# Skittles
skittles <- as.table(rbind(c(80, 87, 59, 70, 60)))
dimnames(skittles) <- list(Colors = c("Red", "Orange", "Yellow", "Green", "Purple"))

chisq.test(skittles)
```

## 10.3-3 Chi-Squared Test of Goodness of Fit 
```{r}
#########################################
############# Chi-Squared ###############
######## Goodness of Fit Test ###########
#########################################

# Reading in a data set of police killings from 2015
police_killings <- read.csv("police_killings_2015.csv")

# Filtering out cases where the race-ethnicity is Unknown 
police_killings <- filter(police_killings, police_killings$raceethnicity != "Unknown")

police_killings_table <- table(police_killings$raceethnicity)

# Because we have an expected pattern for race-ethnicity in the USA, we need to tell R
# what those proportions are. Note: The proprotions must add up to 1. There is some rounding with these numbers 
# so they have been slightly tweeked but not by more than 1% for any group
# The order: Asian = 6%, Black = 13%, Latinx = 16%, Native American = 1%, (Non-Latinx) White = 64%
expected_proportions <- c(.06, .13, .16, .01, .64)

# We then put the UT data and the expected proportions into the "chisq.test()" function  
police_killings_chi_squared <- chisq.test(police_killings_table, p = expected_proportions)
```

