---
title: "Study2 (article)"
author: "Yuya Endo"
date:  "2020-09-18"
output: 
  html_document:
    theme: cerulean
    highlight: tango
    toc: true
    toc_depth: 3
    toc_float: true
    self_contained: true
---

```
## My Session info ##
R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.4

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib

locale:
  ja_JP.UTF-8/ja_JP.UTF-8/ja_JP.UTF-8/C/ja_JP.UTF-8/ja_JP.UTF-8

attached base packages:
  grid      stats     graphics  grDevices utils     datasets  methods  
  base     

other attached packages:
  patchwork_1.0.0 ggstance_0.3.4  cjoint_2.1.0    survey_4.0     
  survival_3.1-12 Matrix_1.2-18   lmtest_0.9-37   zoo_1.8-7      
  sandwich_2.5-1  gt_0.2.0.5      forcats_0.5.0   stringr_1.4.0  
  dplyr_1.0.0     purrr_0.3.4     readr_1.3.1     tidyr_1.1.0    
  tibble_3.0.3    ggplot2_3.3.2   tidyverse_1.3.0
```

#install any necessary packages, inserting package name as appropriate
install.packages("packagename")


```{r, include = FALSE}
knitr::opts_chunk$set(
  warning = FALSE,       
  message = FALSE,      
  comment = "",
  fig.align = "center"  
)
```


```{r road pkg}
library(tidyverse)
library(gt)
library(cjoint)
library(ggstance)
library(patchwork)
```

```{r read data}
df_type1 <- read_csv("data/study2_data_type1.csv")
df_type2 <- read_csv("data/study2_data_type2.csv") 
```


```{r df_conjoint}
df_conjoint <- bind_rows(df_type1, df_type2) %>% 
   mutate(across(where(is.character), as.factor))
```


```{r attribute_list}
attribute_list <- list()
attribute_list[["Sex"]] <- c("Male", "Female")
attribute_list[["Age"]] <- c("44 years old","52 years old","60 years old",
                             "68 years old","76 years old")
attribute_list[["Race/Ethnicity"]] <- c("White","Black",
                                        "Hispanic","Asian American")
attribute_list[["Marital status"]] <- c("Single","Married")
attribute_list[["Parental status"]] <- c("No children","1 child","2 children")
attribute_list[["Experience in legal profession"]] <- c("No experience","5 years",
                                                        "10 years","15 years","20 years")
attribute_list[["Law school ranking"]] <- c("Top 10 (Tier 1)",
                                            "50-100 (Tier 2)","151-200 (Tier 4)")
attribute_list[["Party affiliation"]] <- c("Democratic Party","Republican Party")
```


```{r conjoint_design}
conjoint_design <- makeDesign(type = "constraints",
                              attribute.levels = attribute_list)
```


```{r baselines}
baselines <- list()
baselines[["Sex"]] <- c("Male")
baselines[["Age"]] <- c("44 years old")
baselines[["Race/Ethnicity"]] <- c("White")
baselines[["Marital status"]] <- c("Single")
baselines[["Parental status"]] <- c("No children")
baselines[["Experience in legal profession"]] <- c("No experience")
baselines[["Law school ranking"]] <- c("Top 10 (Tier 1)")
baselines[["Party affiliation"]] <- c("Democratic Party")
```


## Figure 2

```{r acie_partisan}
acie_partisan <- df_conjoint %>% 
  drop_na(Partisanship) %>% 
  filter(type == "type2") %>% 
  amce(selected ~ (Sex + Age + `Race/Ethnicity` + `Marital status` + 
                     `Parental status` + `Experience in legal profession` + 
                     `Law school ranking` + `Party affiliation`) * Partisanship,
               data = ., 
               cluster = TRUE, 
               respondent.id = "respondentIndex", 
               design = conjoint_design, 
               baselines = baselines,
               respondent.varying = c("Partisanship"))
```


```{r base_level function}
base_level <- function(data, mod){
  df_base_pa <- summary(mod)$baselines_amce %>% 
    mutate(
      Level = str_c(Attribute,  ":", "\n", "(", "Baseline = ", Level, ")")
      )
  pa <- data %>%
    mutate(
      lwr = Estimate - 1.96 * `Std. Err`,
      upr = Estimate + 1.96 * `Std. Err`
      ) %>%
    bind_rows(df_base_pa) %>% 
    mutate(
      Level = as.factor(Level),
      Level = factor(Level, 
                     levels = c("Republican Party",
                                "Party affiliation:\n(Baseline = Democratic Party)",
                                "151-200 (Tier 4)",
                                "50-100 (Tier 2)",
                                "Law school ranking:\n(Baseline = Top 10 (Tier 1))",
                                "20 years",
                                "15 years",
                                "10 years",
                                "5 years",
                                "Experience in legal profession:\n(Baseline = No experience)",
                                "2 children",
                                "1 child",
                                "Parental status:\n(Baseline = No children)",
                                "Married",
                                "Marital status:\n(Baseline = Single)",
                                "76 years old",
                                "68 years old",
                                "60 years old",
                                "52 years old",
                                "Age:\n(Baseline = 44 years old)",
                                "Hispanic",
                                "Black",
                                "Asian American",
                                "Race/Ethnicity:\n(Baseline = White)",
                                "Female",
                                "Sex:\n(Baseline = Male)"))
      )
  return(pa)
}
```


```{r}
summary(acie_partisan)$table_values_amce
```


```{r acie_mutate function}
acie_mutate <- function(dat1, dat2, dat3, mod){
    d1 <- dat1 %>% 
        base_level(mod = mod) %>% 
        mutate(Partisanship = "Democrat") 
    d2 <- dat2 %>% 
        base_level(mod = mod) %>% 
        mutate(Partisanship = "Independent") 
    d3 <- dat3 %>% 
        base_level(mod = mod) %>% 
        mutate(Partisanship = "Republican") 
    dd <- bind_rows(d1, d2, d3) %>% 
        mutate(Partisanship = factor(Partisanship, levels = c("Republican",
                                                              "Independent",
                                                              "Democrat")))
    return(dd)
}
```


```{r df_acie_partisan1}
df_acie_partisan <- acie_mutate(summary(acie_partisan)$Partisanship1amce,
                                summary(acie_partisan)$Partisanship2amce,
                                summary(acie_partisan)$Partisanship3amce,
                                mod = acie_partisan) %>% 
  mutate(
    judge_lab = if_else(Partisanship == "Democrat" &
                          Level == "Female",
                        "Judge's attributes", NA_character_),
    Partisanship = str_c("Respondent's\n Partisanship = ", Partisanship)
    )
```


```{r conjoint_plot function}
conjoint_plot <- function(data,
                          ylim, xlim, xlab,
                          facet_vari = NULL,
                          text_x, text_y){
  pl <- data %>% 
    ggplot(., aes(x = Estimate, y = Level,
                  xmin = lwr, xmax = upr), col = "black") +
    geom_vline(xintercept = 0, size = .5, 
               colour = "black", linetype = "dotted") +
    geom_pointrange() +
    coord_cartesian(ylim = ylim, xlim = xlim, clip = 'off') +
    labs(x = xlab, y = NULL) +
    theme(legend.position = "none",
          axis.text = element_text(size = 11),
          axis.title = element_text(size = 12),
          plot.margin = unit(c(1, 1, 0, 1), "lines"))
  
  if(is.null(facet_vari)){
    pl <- pl +
      geom_text(x = text_x, y = text_y, hjust = 0, col = "black",
                size = 4,
                label = "Judge's attributes", show.legend = FALSE)
    return(pl)
  } else {
    facet_vari <- sym(facet_vari)
    pl <- pl +
      facet_wrap(facet_vari, ncol = 3) +
      geom_text(data = data,
                x = text_x, y = text_y, hjust = 0, col = "black",
                size = 4,
                label = data$judge_lab, show.legend = FALSE)
    return(pl)
  }
}
```

```{r pl_acie_partisan, fig.width=10, fig.height=10}
pl_acie_partisan <- df_acie_partisan %>% 
  ggplot(., aes(x = Estimate, y = Level,
                xmin = lwr, xmax = upr), col = "black") +
  geom_vline(xintercept = 0, size = .5, 
             colour = "black", linetype = "dotted") +
  geom_pointrange() +
  facet_wrap(~ Partisanship, ncol = 3) +
  geom_text(data = df_acie_partisan,
            x = -.49, y = 26.7, hjust = 0, col = "black",
            size = 4,
            label = df_acie_partisan$judge_lab, show.legend = FALSE) +
  coord_cartesian(ylim = c(1, 26.5), xlim = c(-.2, .23), clip = 'off') +
  labs(x = "Change in Pr(Biased judge)", y = NULL) +
  theme(legend.position = "none",
        axis.text = element_text(size = 11),
        axis.title = element_text(size = 12),
        plot.margin = unit(c(1, 1, 0, 1), "lines"))

pl_acie_partisan
```


```{r save Figure2}
ggsave("output_figure/paper/Figure2.png", pl_acie_partisan, width = 10, height = 10)
```


## Figure 3

```{r acie_partisan_case}
acie_partisan_case <- df_conjoint %>% 
  drop_na(Partisanship) %>% 
  filter(type == "type2") %>%
  split(.$Condition) %>% 
  map(~ amce(selected ~ (Sex + 
                           Age + 
                           `Race/Ethnicity` + 
                           `Marital status` + 
                           `Parental status` + 
                           `Experience in legal profession` + 
                           `Law school ranking` + 
                           `Party affiliation`) * Partisanship,
             data = ., 
             cluster = TRUE, 
             respondent.id = "respondentIndex", 
             design = conjoint_design, 
             baselines = baselines,
             respondent.varying = c("Partisanship"))
      )
```



```{r conjoint_mutate}
conjoint_mutate <- function(data,
                            p1 = "", p2 = "", p3 = "",
                            xlim, xlab = ""){
  cm <- data %>% 
    mutate(
      Partisanship = c(rep(p1, nrow(.) / 3),
                       rep(p2, nrow(.) / 3),
                       rep(p3, nrow(.) / 3)),
      Partisanship = factor(Partisanship, levels = c("Republican",
                                                     "Independent",
                                                     "Democrat")),
      lwr = Estimate - 1.96 * `Std. Err`,
      upr = Estimate + 1.96 * `Std. Err`
      ) %>% 
    filter(Level %in% c("Female", "Hispanic")) %>% 
    mutate(
      judge = if_else(Level == "Female", "Female Judge", "Hispanic Judge")
    ) 
  pl <- cm %>% 
    mutate(judge = fct_rev(fct_inorder(judge))) %>% 
    ggplot(aes(x = Estimate, y = Partisanship, shape = judge, color = judge,
               xmin = lwr, xmax = upr)) +
    geom_vline(xintercept = 0, size = 1,
               colour = "gray75", linetype = "solid") +
    geom_pointrangeh(position = position_dodgev(height = .75), size = .65) +
    labs(x = xlab, y = NULL) +
    xlim(xlim) +
    scale_colour_manual(name = "Judge",
                        values = c(`Female Judge` = "black",
                                   `Hispanic Judge` = "grey60"),
                        guide = guide_legend(reverse = TRUE)) + 
    scale_shape_manual(name = "Judge",
                       values = c(`Female Judge` = 15,
                                  `Hispanic Judge` = 17),
                       guide = guide_legend(reverse = TRUE)) +
    theme(legend.position = "bottom",
          legend.key = element_rect(fill = "white"),
          axis.text = element_text(size = 11))
  
    return(pl)
}
```

```{r}
summary(acie_partisan_case$Conjoint1)$table_values_amce
```

```{r pl_abortion}
pl_abortion <- bind_rows(summary(acie_partisan_case$Conjoint1)$Partisanship1amce,
                         summary(acie_partisan_case$Conjoint1)$Partisanship2amce,
                         summary(acie_partisan_case$Conjoint1)$Partisanship3amce) %>%
  conjoint_mutate(p1 = "Democrat", p2 = "Independent", p3 = "Republican",
                  xlim = c(-.11, .11), xlab = "Change in Pr(Biased judge)")
pl_abortion
```


```{r save Figure3}
ggsave("output_figure/paper/Figure3.png", pl_abortion, width = 6, height = 2.8)
```

## Part 3: Separated Conjoint Results for Immigration Case (Figure 4)

```{r}
summary(acie_partisan_case$Conjoint2)$table_values_amce
```

```{r pl_immigration}
pl_immigration <- bind_rows(summary(acie_partisan_case$Conjoint2)$Partisanship1amce,
                            summary(acie_partisan_case$Conjoint2)$Partisanship2amce,
                            summary(acie_partisan_case$Conjoint2)$Partisanship3amce) %>%
  conjoint_mutate(p1 = "Democrat", p2 = "Independent", p3 = "Republican",
                  xlim = c(-.23, .23), xlab = "Change in Pr(Biased judge)")
pl_immigration
```


```{r save Figure4}
ggsave("output_figure/paper/Figure4.png", pl_immigration, width = 6, height = 2.8)
```
