R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

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.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ 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
## Warning: 程辑包'infer'是用R版本4.3.2 来建造的
## [[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")

###Task1

Switzerland_data <- ess %>%
  filter(cntry == "CH") %>%
  
  mutate(
    brncntr = case_when(
      brncntr == 1 ~ "Yes",
      brncntr == 2 ~ "No",
      brncntr %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(brncntr)),
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
    
    
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    
    
    edulvlb = case_when(
      essround >= 5 & edulvlb == 5555 ~ NA_real_,
      TRUE ~ edulvlb
    ),
    
    
    educ_level = case_when(
      essround < 5 & edulvla == 5 ~ "BA",
      essround >= 5 & edulvlb > 600 ~ "BA",
      TRUE ~ "No BA"
    ),
  )
unique(Switzerland_data$brncntr)
## [1] "No"  "Yes" NA
Switzerland_data <- Switzerland_data %>% filter(!is.na(brncntr))
Switzerland_data <- Switzerland_data %>% filter(!is.na(educ_level))

unique(Switzerland_data$brncntr)
## [1] "No"  "Yes"
table(Switzerland_data$brncntr)
## 
##    No   Yes 
##  3867 13056
CHtab <- table(Switzerland_data$brncntr, Switzerland_data$educ_level)

rsums <- rowSums(CHtab)
csums <- colSums(CHtab)

N <- sum(CHtab)

CHptab <- tcrossprod(rsums/N, csums/N)
cat("Table of Expected Proportions:\n")
## Table of Expected Proportions:
print(CHptab)
##            [,1]      [,2]
## [1,] 0.05206627 0.1764393
## [2,] 0.17578931 0.5957051
CHftab <- N*CHptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(CHftab)
##           [,1]      [,2]
## [1,]  881.1175  2985.882
## [2,] 2974.8825 10081.118
alpha <- 0.05
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3))
## Critical Value: 3.841

Interpretation: If the Chi-squared test statistic exceeds 3.841, then we reject the null hypothesis at the 0.05 significance level. This would mean that there is a statistically significant association between feeling close to a party and education level in dataset.

CH_stat <- sum((CHtab - CHftab)^2 / CHftab)
cat("Pearson's X^2:", round(CH_stat, 4), "\n")
## Pearson's X^2: 65.1218

Comparison to the critical value: We previously calculated a critical value of 3.841. Our observed X-squared value 65,1218 is much larger than this critical value. Interpretation: The difference between our observed data 65.1218 and what we’d expect under the assumption of independence is statistically significant. Thus, there is a statistically significant association between feeling close to a party and one’s educational level. This means that the probability of feeling close to a party is not the same across different education levels.

p_val <- pchisq(CH_stat, df = 1, lower.tail = F)
cat("p-value:", round(p_val, 4), "\n")
## p-value: 0
cat("Chi-squared test result:\n")
## Chi-squared test result:
print(chisq.test(CHtab, correct = F))
## 
##  Pearson's Chi-squared test
## 
## data:  CHtab
## X-squared = 65.122, df = 1, p-value = 7.041e-16

p-value = 7.041e-16: This is another representation of the p-value in scientific notation because it’s extremely close to 0.

The chi-squared test tells us if two categorical variables are independent or if they are associated in some manner. In our test: The extremely small p-value (essentially 0) means that we reject the null hypothesis 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 CHtab.

###Task2

Netherlands_data <- ess %>%
  filter(cntry == "NL") %>%
  
  mutate(
    gincdif = case_when(
      gincdif == 1 ~ "Agree Strongly",
      gincdif == 2 ~ "Agree",
      gincdif == 3 ~ "Neither Agree nor Disagree",
      gincdif == 4 ~ "Disagree",
      gincdif == 5 ~ "Disagree Strongly",
      gincdif %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(gincdif)),
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
    
    
    domicil = case_when(
      domicil == 1 ~ "Urban",
      domicil == 2 ~ "Urban",
      domicil == 3 ~ "Rural",
      domicil == 4 ~ "Rural",
      domicil == 5 ~ "Rural",
      domicil %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(domicil)),
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
    )
table(Netherlands_data$domicil)
## 
## Rural Urban 
## 12681  5623