link: file:///Users/sss/Desktop/soc202/HW7/HW7-Ruoci.html
# List of packages
packages <- c("tidyverse", "infer", "fst") # add any you need here
# Install packages if they aren't installed already
new_packages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(new_packages)) install.packages(new_packages)
# Load the packages
lapply(packages, library, character.only = TRUE)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.4 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.3 ✔ tibble 3.2.1
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ✔ purrr 1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
## [[1]]
## [1] "lubridate" "forcats" "stringr" "dplyr" "purrr" "readr"
## [7] "tidyr" "tibble" "ggplot2" "tidyverse" "stats" "graphics"
## [13] "grDevices" "utils" "datasets" "methods" "base"
##
## [[2]]
## [1] "infer" "lubridate" "forcats" "stringr" "dplyr" "purrr"
## [7] "readr" "tidyr" "tibble" "ggplot2" "tidyverse" "stats"
## [13] "graphics" "grDevices" "utils" "datasets" "methods" "base"
##
## [[3]]
## [1] "fst" "infer" "lubridate" "forcats" "stringr" "dplyr"
## [7] "purrr" "readr" "tidyr" "tibble" "ggplot2" "tidyverse"
## [13] "stats" "graphics" "grDevices" "utils" "datasets" "methods"
## [19] "base"
ess <- read_fst("All-ESS-Data.fst")
table(ess$cntry)
##
## AL AT BE BG CH CY CZ DE DK EE ES FI FR
## 1201 15225 17451 13240 16925 6065 20090 34425 12408 16856 19452 19532 19038
## GB GR HR HU IE IL IS IT LT LU LV ME MK
## 20979 12558 6535 16642 22233 16218 3975 10178 11652 3187 3921 2478 1429
## NL NO PL PT RO RS RU SE SI SK TR UA XK
## 18329 16065 17689 17881 2146 3548 12458 18216 13484 11292 4272 9987 1295
Set up the calculations for an exploration of educ_level (as BA, No BA) and brncntr (recoded as yes/no *shown in tutorial 4) for Switzerland. Using the steps outlined in the tutorial, first generate the tables of expected proportions and frequencies. Determine and interpret the critical value for independence. Finally, determine and interpret both the Pearson’s chi-squared statistic and the p-value. Discuss main takeaways.
switzerland_data <- ess %>%
filter(cntry == "CH") %>%
mutate(
brncntr = case_when(
brncntr == 1 ~ "Yes", # Recode 1 to "Yes"
brncntr == 2 ~ "No", # Recode 2 to "No"
brncntr %in% c(7, 8, 9) ~ NA_character_, # Handle other specific cases where you want to set it as NA
TRUE ~ as.character(brncntr) # Keep other values as-is but ensure they are characters
),
# Recoding education for rounds 1-4
edulvla = case_when(
essround < 5 & edulvla == 55 ~ NA_real_,
TRUE ~ edulvla
),
# Re-coding education for rounds 5 and later
edulvlb = case_when(
essround >= 5 & edulvlb == 5555 ~ NA_real_,
TRUE ~ edulvlb
),
# Create educ_level column
educ_level = case_when(
essround < 5 & edulvla == 5 ~ "BA",
essround >= 5 & edulvlb > 600 ~ "BA",
TRUE ~ "No BA"
)
)
tab_dat <- switzerland_data
# Create a crosstable and save it into the object mytab
mytab <- table(tab_dat$cntry, tab_dat$educ_level)
# Calculate row-wise sums of counts in table
rsums <- rowSums(mytab)
# Calculate column-wise sums of counts in table
csums <- colSums(mytab)
# Get the total count of the table (N)
N <- sum(mytab)
# Generate table of expected proportions
ptab <- tcrossprod(rsums/N, csums/N)
cat("Table of Expected Proportions:\n")
## Table of Expected Proportions:
print(ptab)
## [,1] [,2]
## [1,] 0.2278287 0.7721713
# Table of expected frequencies
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
## [,1] [,2]
## [1,] 3856 13069
# Critical Value for Independence:
alpha <- 0.05 # significance level
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841
critical value:3.841 Interpreting: If the Chi-squared test statistic that you comoute exceeds 3.841, then we reject the null hypothesis at the 0.05 sianificance level, This would mean that there is a statistically sianificant associction between feeling close to a party and education level in your dataset
# Pearson's chi-squared statistic:
test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 0
# p-value:
p_val <- pchisq(test_stat, df = 1, lower.tail = F)
cat("p-value:", round(p_val, 4), "\n")
## p-value: 1
# Using chisq.test for validation:
cat("Chi-squared test result:\n")
## Chi-squared test result:
print(chisq.test(mytab, correct = F))
##
## Chi-squared test for given probabilities
##
## data: mytab
## X-squared = 5015, df = 1, p-value < 2.2e-16
p-value < 2.2e-16 which is extremely close to 0. So we reject Null Hypothesis (H0) that the two variables are independent of each other. In other words, there’s strong evidence to suggest that there’s a significant association between the two variables in mytab. The large chi-squared statistic of 5015 further reinforces this point. If the two variables were independent, we’d expect a chi-squared statistic closer to 0.
Using the infer package and following the 4 steps outlined in the tutorial and during the lecture, conduct and visualize the hypothesis testing for domicil (recoded as urban/rural – see tutorial 4) and gincdif (Government should reduce differences in income levels) for the country of Netherlands. For gincdif, you must recode for the five categories (i.e, cannot keep as numeric).
See variable info here:
https://ess-search.nsd.no/en/variable/1ad9f42e-0c02-4b13-9a67-ee83d82ac576
Make decision over appropriate test given table provided during lecture. After conducting the 4 steps, interpret all the output and discuss your takeaways.
netherlands_data <- ess %>%
filter(cntry == "NL") %>%
mutate(geo = recode(as.character(domicil),
'1' = "Urban",
'2' = "Urban",
'3' = "Rural",
'4' = "Rural",
'5' = "Rural",
'7' = NA_character_,
'8' = NA_character_,
'9' = NA_character_))
netherlands_data <- netherlands_data %>%
mutate(geo = recode(as.character(gincdif),
'1' = "Agree strongly",
'2' = "Agree",
'3' = "Neither agree nor disagree",
'4' = "Disagree",
'5' = "Disagree strongly",
'7' = NA_character_,
'8' = NA_character_,
'9' = NA_character_))
netherlands_data <- ess %>%
filter(cntry == "NL") %>%
mutate(geo_domicil = recode(as.character(domicil),
'1' = "Urban",
'2' = "Urban",
'3' = "Rural",
'4' = "Rural",
'5' = "Rural",
'7' = NA_character_,
'8' = NA_character_,
'9' = NA_character_),
geo_gincdif = recode(as.character(gincdif),
'1' = "Agree strongly",
'2' = "Agree",
'3' = "Neither agree nor disagree",
'4' = "Disagree",
'5' = "Disagree strongly",
'7' = NA_character_,
'8' = NA_character_,
'9' = NA_character_))
NL_stat <- netherlands_data %>%
specify(geo_gincdif ~ geo_domicil) %>%
calculate(stat = "chisq")
## Warning: Removed 198 rows containing missing values.
print(NL_stat)
## Response: geo_gincdif (factor)
## Explanatory: geo_domicil (factor)
## # A tibble: 1 × 1
## stat
## <dbl>
## 1 8.18
Interpretation: A t-statistic of 8.17 is quite large, indicating a significant difference in opinion of Government should reduce differences in income levels between urban and rural.
null_distribution <- netherlands_data %>%
specify(geo_gincdif ~ geo_domicil) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>% # only line we are adding, use reps = 1000 as standard
calculate(stat = "chisq")
## Warning: Removed 198 rows containing missing values.
p_val <- null_distribution %>% # replace name here if you assigned something other than null_distribution above
get_pvalue(obs_stat = NL_stat, direction = "two-sided") # would only replace test_stat if assigned another name in Step 1
p_val
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0.206
can reject the null.
null_distribution %>%
visualize() +
shade_p_value(obs_stat = NL_stat, direction = "two-sided")
## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.
null_distribution
## Response: geo_gincdif (factor)
## Explanatory: geo_domicil (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.675
## 2 2 11.1
## 3 3 1.08
## 4 4 0.554
## 5 5 1.15
## 6 6 3.07
## 7 7 2.90
## 8 8 2.15
## 9 9 0.599
## 10 10 2.87
## # ℹ 990 more rows
conf_int <- null_distribution %>%
get_confidence_interval(level = 0.95, type = "percentile")
null_distribution %>%
visualize() +
shade_p_value(obs_stat = NL_stat, direction = "two-sided") +
shade_confidence_interval(endpoints = conf_int)
## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.
null_distribution
## Response: geo_gincdif (factor)
## Explanatory: geo_domicil (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.675
## 2 2 11.1
## 3 3 1.08
## 4 4 0.554
## 5 5 1.15
## 6 6 3.07
## 7 7 2.90
## 8 8 2.15
## 9 9 0.599
## 10 10 2.87
## # ℹ 990 more rows
red line fall within the CI so it can’t reject the null hypothesis. there is no difference between urban and rural in whether Government should reduce differences in income levels
First, talk about a research question you would like to consider, which identifies a main relationship between an explanatory variable and an outcome variable. Using the infer package and following the 4 steps outlined in the tutorial and during the lecture, conduct and visualize the hypothesis testing for your variables based on your research question. After conducting the 4 steps, interpret all the output and discuss your takeaways.
france_data <- ess %>%
# Filter for France
filter(cntry == "FR") %>%
mutate(
stfgov = ifelse(stfgov %in% c(77, 88, 99), NA, stfgov)
) %>%
# Recoding gender
mutate(
gndr = case_when(
gndr == 1 ~ "Male",
gndr == 2 ~ "Female",
gndr == 9 ~ NA_character_,
TRUE ~ as.character(gndr)
)
)
test_stat <- france_data %>%
specify(explanatory = gndr, # change variable name for explanatory variable
response = stfgov) %>% # change variable name for outcome of interest
hypothesize(null = "independence") %>%
calculate(stat = "t") # replace in between quotation marks appropriate test statistic
## Warning: Removed 280 rows containing missing values.
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "Female" - "Male", or divided in the order "Female" / "Male" for
## ratio-based statistics. To specify this order yourself, supply `order =
## c("Female", "Male")` to the calculate() function.
print(test_stat$stat)
## t
## 0.2066718
null_gender <- france_data %>%
specify(explanatory = gndr,
response = stfgov) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>% # only line we are adding, use reps = 1000 as standard
calculate(stat = "t")
## Warning: Removed 280 rows containing missing values.
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "Female" - "Male", or divided in the order "Female" / "Male" for
## ratio-based statistics. To specify this order yourself, supply `order =
## c("Female", "Male")` to the calculate() function.
p_val <- null_distribution %>% # replace name here if you assigned something other than null_distribution above
get_pvalue(obs_stat = test_stat, direction = "two-sided") # would only replace test_stat if assigned another name in Step 1
p_val
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0.016
it’s close to 0, which can reject null
null_gender %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided")
null_gender
## Response: stfgov (numeric)
## Explanatory: gndr (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 -1.16
## 2 2 0.795
## 3 3 0.369
## 4 4 -0.975
## 5 5 -0.220
## 6 6 -1.37
## 7 7 1.07
## 8 8 1.20
## 9 9 0.0845
## 10 10 -0.304
## # ℹ 990 more rows
conf_int <- null_distribution %>%
get_confidence_interval(level = 0.95, type = "percentile")
null_gender %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided") +
shade_confidence_interval(endpoints = conf_int)
null_gender
## Response: stfgov (numeric)
## Explanatory: gndr (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 -1.16
## 2 2 0.795
## 3 3 0.369
## 4 4 -0.975
## 5 5 -0.220
## 6 6 -1.37
## 7 7 1.07
## 8 8 1.20
## 9 9 0.0845
## 10 10 -0.304
## # ℹ 990 more rows
the red line fall outside the CI so it can reject the null hypothesis. there are differences between female and male in How satisfied with the national government.