library(haven)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ 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
library(dplyr)
library(kableExtra)
## 
## Attaching package: 'kableExtra'
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows
setwd("/Users/karenvillanueva/Downloads")
data =  read_dta("Pew July 13 2013.dta")

data = data %>%
  mutate(Education = case_when(
    educ2 == 1 ~ 10,
    educ2 == 2 ~ 10,
    educ2 == 3 ~ 11,
    educ2 == 4 ~ 12,
    educ2 == 5 ~ 12,
    educ2 == 6 ~ 13,
    educ2 == 7 ~ 13,
    educ2 == 8 ~ 14,
    party %in% c(9) ~ NA
  ))

data %>%
  filter(q33 %in% c(1,2,3,4)) %>%
  filter(Education %in% c(10,11,12,13,14)) %>%
  mutate(q33 = as_factor(q33,levels="labels")) %>%
  group_by(Education,q33) %>%
  summarise(count = n()) %>%
  mutate(share = count/sum(count)) %>%
  select(-count) %>%
  mutate(share = round(share*100,2),
         share = paste0(share,"%")) %>%
  mutate(Education = case_when(
    Education == 10 ~ '(1) Some high school or less',
    Education == 11 ~ '(2) High school graduate',
    Education == 12 ~ '(3) Some college or 2-year degree',
    Education == 13 ~ '(4) 4-year college or university degree',
    Education == 14 ~ '(5) Graduate or professional degree',
    TRUE ~ NA
  )) %>%
  spread(q33,share) %>%
  kable(format='html', booktabs=TRUE, 
        caption=
          "Rating of 2013 U.S. economic conditions by education level.") %>%
  add_header_above(header = c(" " = 1, "Economic conditions rating" = 4)) %>%
  kable_styling(bootstrap_options = "bordered")
## `summarise()` has grouped output by 'Education'. You can override using the
## `.groups` argument.
Rating of 2013 U.S. economic conditions by education level.
Economic conditions rating
Education Excellent Good Only fair Poor
  1. Some high school or less
6.45% 15.05% 47.31% 31.18%
  1. High school graduate
0.78% 16.41% 41.93% 40.89%
  1. Some college or 2-year degree
0.74% 14.11% 42.08% 43.07%
  1. 4-year college or university degree
1.67% 16.99% 50.42% 30.92%
  1. Graduate or professional degree
1.38% 17.97% 52.53% 28.11%