---
title: "Study2 (Appendix)"
author: "Yuya Endo"
date:  "2020-11-12"
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
```

```{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))
```


## Sample Characteristics

```{r df_samp_freq}
df_samp_freq <- df_type2 %>% 
    select(Age = agegroup, Race = R_race, Hispanic, Male) %>% 
    mutate(
        Ethnicity = if_else(Hispanic == 1, "Hispanic", "Non-Hispanic"),
        Gender = if_else(Male == 1, "Male", "Female")
    ) %>% 
    select(Age, Race, Ethnicity, Gender) %>% 
    pivot_longer(Age:Gender,
                 names_to = "variable", values_to = "value") %>% 
    group_by(variable) %>% 
    count(value) %>% 
    mutate(
        freq　=　n/sum(n)*100,
        variable = factor(variable, levels = c("Age", "Race",
                                               "Ethnicity", "Gender"))
        )
```


```{r tb_samp_freq}
tb_samp_freq <- df_samp_freq %>% 
    select(variable, value, freq) %>% 
    mutate(freq = round(freq, 2)) %>% 
    rename(Characteristic = value, `Proportion of Sample` = freq) %>% 
  　mutate(Characteristic = fct_relevel(Characteristic,
  　                                    c("18-25", "26-35", "36-45", "46-55",
  　                                      "56-65", "66 or older", "White",
  　                                      "Black", "Hispanic", "Asian",
  　                                      "Other", "Hispanic", "Non-Hispanic",
  　                                      "Male", "Female"))) %>% 
    arrange(Characteristic) %>% 
    gt(rowname_col = "row",
       groupname_col = "variable") %>% 
    cols_label(`Proportion of Sample` = html("Proportion of <br> Sample")) %>% 
    row_group_order(groups = c("Age", "Race", "Ethnicity", "Gender"))

tb_samp_freq 
```




```{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")
```


## Part 1: Pooled Conjoint Results by Respondent’s Partisanship (Figure 2)

```{r acie_partisan}
acie_partisan <- df_conjoint %>% 
    drop_na(Partisanship) %>% 
    split(.$type) %>% 
    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 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$type1)$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_partisan1 <- acie_mutate(summary(acie_partisan$type1)$Partisanship1amce,
                                 summary(acie_partisan$type1)$Partisanship2amce,
                                 summary(acie_partisan$type1)$Partisanship3amce,
                                 mod = acie_partisan$type1) %>% 
    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_partisan1, fig.width=10, fig.height=10}
pl_acie_partisan1 <- df_acie_partisan1 %>%
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.15, .2),
                xlab = "Change in Pr(Self value influence judge)",
                facet_vari = "Partisanship",
                text_x = -.38, text_y = 26.7)

pl_acie_partisan1
```


```{r save Part1}
ggsave("output_figure/appendix/Part1.png", pl_acie_partisan1, width = 10, height = 10)
```


## Part 2: Separated Conjoint Results for Abortion Case (Figure 3)

```{r acie_partisan_case}
acie_partisan_case <- df_conjoint %>% 
    drop_na(Partisanship) %>% 
    split(list(.$type ,.$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$type1.Conjoint1)$table_values_amce
```

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


```{r save pl_part2}
ggsave("output_figure/appendix/Part2.png", pl_part2, width = 6, height = 2.8)
```

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

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

```{r pl_part3}
pl_part3 <- bind_rows(summary(acie_partisan_case$type1.Conjoint2)$Partisanship1amce,
                      summary(acie_partisan_case$type1.Conjoint2)$Partisanship2amce,
                      summary(acie_partisan_case$type1.Conjoint2)$Partisanship3amce) %>%
  conjoint_mutate(p1 = "Democrat", p2 = "Independent", p3 = "Republican",
                  xlim = c(-.2, .2), xlab = "Change in Pr(Personal values)")

pl_part3
```

```{r save pl_part3}
ggsave("output_figure/appendix/Part3.png", pl_part3, width = 6, height = 2.8)
```

## Part 4: Pooled AMCEs

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


```{r df_acie_pool1}
df_acie_pool1 <- summary(acie_pool$type1)$amce %>% 
    base_level(mod = acie_pool$type1) %>% 
    mutate(
        judge_lab = if_else(Level == "Female", "Judge's attributes", NA_character_)
        )
```


```{r pl_acie_pool1, fig.width=10, fig.height=10}
pl_acie_pool1 <- df_acie_pool1 %>% 
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.1, .1),
                xlab = "Change in Pr(Self value influence judge)",
                text_x = -.38, text_y = 26.7)

pl_acie_pool1
```

```{r save Part4_a}
ggsave("output_figure/appendix/Part4_a.png", pl_acie_pool1, width = 10, height = 10)
```

### (b) Average Marginal Component Effects (judge is biased)

```{r df_acie_pool2}
df_acie_pool2 <- summary(acie_pool$type2)$amce %>% 
    base_level(mod = acie_pool$type2) %>% 
    mutate(
        judge_lab = if_else(Level == "Female", "Judge's attributes", NA_character_)
        )
```


```{r pl_acie_pool2, fig.width=10, fig.height=10}
pl_acie_pool2 <- df_acie_pool2 %>% 
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.15, .15),
                xlab = "Change in Pr(Biased judge)",
                text_x = -.22, text_y = 26.7)

pl_acie_pool2
```


```{r save Part4_b}
ggsave("output_figure/appendix/Part4_b.png", pl_acie_pool2, width = 10, height = 10)
```

## Part 5: Separated AMCEs – Abortion Case

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

### (a) Average Marginal Component Effects in Abortion Case (personal values influence decisions)

```{r df_acie_pool_case1}
df_acie_pool_case1 <- summary(acie_pool_case$type1.Conjoint1)$amce %>% 
    base_level(mod = acie_pool_case$type1.Conjoint1) %>% 
    mutate(
        judge_lab = if_else(Level == "Female", "Judge's attributes", NA_character_)
        )
```

```{r pl_acie_pool_case1, fig.width=10, fig.height=10}
pl_acie_pool_case1 <- df_acie_pool_case1 %>% 
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.1, .1),
                xlab = "Change in Pr(Self value influence judge)",
                text_x = -.147, text_y = 26.7)

pl_acie_pool_case1
```


```{r save Part5_a}
ggsave("output_figure/appendix/Part5_a.png", pl_acie_pool_case1, width = 10, height = 10)
```


### (b) Average Marginal Component Effects in Abortion Case (judge is biased)

```{r df_acie_pool_case2}
df_acie_pool_case2 <- summary(acie_pool_case$type2.Conjoint1)$amce %>% 
    base_level(mod = acie_pool_case$type2.Conjoint1) %>% 
    mutate(
        judge_lab = if_else(Level == "Female", "Judge's attributes", NA_character_)
        )
```


```{r pl_acie_pool_case2, fig.width=10, fig.height=10}
pl_acie_pool_case2<- df_acie_pool_case2 %>% 
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.15, .1),
                xlab = "Change in Pr(Biased judge)",
                text_x = -.21, text_y = 26.7)

pl_acie_pool_case2
```


```{r save Part5_b}
ggsave("output_figure/appendix/Part5_b.png", pl_acie_pool_case2, width = 10, height = 10)
```

## Part 6: Separated AMCEs – Immigration Case
### (a) Average Marginal Component Effects in Immigration Case (personal values influence decisions)

```{r df_acie_pool_case11}
df_acie_pool_case11 <- summary(acie_pool_case$type1.Conjoint2)$amce %>% 
    base_level(mod = acie_pool_case$type1.Conjoint2) %>% 
    mutate(
        judge_lab = if_else(Level == "Female", "Judge's attributes", NA_character_)
        )
```

```{r pl_acie_pool_case11, fig.width=10, fig.height=10}
pl_acie_pool_case11 <- df_acie_pool_case11 %>% 
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.1, .1),
                xlab = "Change in Pr(Self value influence judge)",
                text_x = -.147, text_y = 26.7)

pl_acie_pool_case11
```


```{r save Part6_a}
ggsave("output_figure/appendix/Part6_a.png", pl_acie_pool_case11, width = 10, height = 10)
```

### (b) Average Marginal Component Effects in Immigration Case (judge is biased)

```{r df_acie_pool_case22}
df_acie_pool_case22 <- summary(acie_pool_case$type2.Conjoint2)$amce %>% 
    base_level(mod = acie_pool_case$type2.Conjoint2) %>% 
    mutate(
        judge_lab = if_else(Level == "Female", "Judge's attributes", NA_character_)
        )
```

```{r pl_acie_pool_case22, fig.width=10, fig.height=10}
pl_acie_pool_case22 <- df_acie_pool_case22 %>% 
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.15, .1),
                xlab = "Change in Pr(Biased judge)",
                text_x = -.21, text_y = 26.7)

pl_acie_pool_case22
```


```{r save Part6_b}
ggsave("output_figure/appendix/Part6_b.png", pl_acie_pool_case22, width = 10, height = 10)
```


## Part 7: Full ACIEs for Figure 3
### (a) Average Component Interactive Effects in Abortion Case (personal values influence decisions)

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


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


```{r pl_acie_partisan_case1, fig.width=10, fig.height=10}
pl_acie_partisan_case1 <- df_acie_partisan_case1 %>% 
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.13, .2),
                xlab = "Change in Pr(Self value influence judge)",
                facet_vari = "Partisanship",
                text_x = -.335, text_y = 26.7)

pl_acie_partisan_case1
```


```{r save Part7_a}
ggsave("output_figure/appendix/Part7_a.png",
       pl_acie_partisan_case1, width = 10, height = 10)
```


### (b) Average Component Interactive Effects in Abortion Case (judge is biased)

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


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


```{r pl_acie_partisan_case2, fig.width=10, fig.height=10}
pl_acie_partisan_case2 <- df_acie_partisan_case2 %>% 
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.2, .3),
                xlab = "Change in Pr(Biased judge)",
                facet_vari = "Partisanship",
                text_x = -.52, text_y = 26.7)

pl_acie_partisan_case2
```


```{r save Part7_b}
ggsave("output_figure/appendix/Part7_b.png",
       pl_acie_partisan_case2, width = 10, height = 10)
```

## Part 8: Full ACIEs for Figure 4
### (a) Average Component Interactive Effects in Immigration Case (personal values influence decisions)

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


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

```{r pl_acie_partisan_case11, fig.width=10, fig.height=10}
pl_acie_partisan_case11 <- df_acie_partisan_case11 %>% 
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.13, .2),
                xlab = "Change in Pr(Self value influence judge)",
                facet_vari = "Partisanship",
                text_x = -.34, text_y = 26.7)

pl_acie_partisan_case11
```


```{r save Part8_a}
ggsave("output_figure/appendix/Part8_a.png",
       pl_acie_partisan_case11, width = 10, height = 10)
```

### (b) Average Component Interactive Effects in Immigration Case (judge is biased)

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


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


```{r pl_acie_partisan_case22, fig.width=10, fig.height=10}
pl_acie_partisan_case22 <- df_acie_partisan_case22 %>% 
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.2, .3),
                xlab = "Change in Pr(Biased judge)",
                facet_vari = "Partisanship",
                text_x = -.52, text_y = 26.7)

pl_acie_partisan_case22
```


```{r save Part8_b}
ggsave("output_figure/appendix/Part8_b.png", 
       pl_acie_partisan_case22, width = 10, height = 10)
```

## Part 9: Comparison between a Republican Judge and a Democratic Judge

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


```{r base_level_pa function}
base_level_pa <- function(data, type = ""){
  df_base_pa <- summary(acie_pa$type1)$baselines_acie %>% 
    mutate(
      Attribute = str_remove_all(Attribute, c("Party affiliation" = "", ":" = "")),
      Level = str_remove_all(Level, c("Democratic Party" = "", ":" = "")),
      Level = str_c(Attribute,  ":", "\n", "(", "Baseline = ", Level, ")")
      )
  pa <- data %>%
    mutate(
      Attribute = str_remove_all(Attribute, c("Party affiliation" = "", ":" = "")),
      Level = str_remove_all(Level, c("Republican Party" = "", ":" = "")),
      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("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)")),
      type = type
      )
  return(pa)
}
```


```{r df_acie_pa}
df_acie_pa1 <- summary(acie_pa$type1)$acie %>% 
  base_level_pa(type = "(a) ACIE (personal values influence decisions)")
df_acie_pa2 <- summary(acie_pa$type2)$acie %>% 
  base_level_pa(type = "(b) ACIE (judge is biased)")
df_acie_pa <- bind_rows(df_acie_pa1, df_acie_pa2) %>% 
  mutate(
      judge_lab = if_else(Level == "Female", 
                          "Judge's attributes", NA_character_),
      Party_affiliation = "ACIE\n Party affiliation = Republican Party"
      )
```


```{r pl_acie_pa, fig.width=10, fig.height=10}
pl_acie_pa <- df_acie_pa %>% 
  group_nest(type) %>% 
  mutate(
    gg = map(data, ~ ggplot(., aes(x = Estimate, y = Level,
                                   xmin = lwr, xmax = upr), col = "black") +
               facet_wrap(~ Party_affiliation, ncol = 4) +
               geom_vline(xintercept = 0, size = .5, 
                          colour = "black", linetype = "dotted") +
               geom_pointrange() +
               coord_cartesian(ylim = c(1, 24.5),
                               xlim = c(-.1, .1), clip = 'off') +
               ylab(NULL) +
               theme(legend.position = "none",
                     axis.text = element_text(size = 11),
                     plot.margin = unit(c(1, 1, 0, 1), "lines"),
                     plot.title = element_text(size = 12, hjust = 0.5))),
    gg = map2(gg, type, ~ .x + labs(title = .y))
    )

pl_acie_pa <- wrap_plots(pl_acie_pa$gg) 
pl_acie_pa[[1]] <- pl_acie_pa[[1]] +
     geom_text(data = df_acie_partisan_case22,
                         x = -.19, y = 24.7, hjust = 0, col = "black",
                         size = 4,
                         label = df_acie_partisan_case22$judge_lab, 
                         show.legend = FALSE) +
    xlab("Change in Pr(Self value influence judge)")
pl_acie_pa[[2]] <- pl_acie_pa[[2]] + 
    xlab("Change in Pr(Biased judge)") +
    theme(axis.text.y = element_blank())
pl_acie_pa
```


```{r save Part9_ab}
ggsave("output_figure/appendix/Part9_ab.png", pl_acie_pa, width = 10, height = 10)
```


### Average Component Interactive Effects (personal values influence decisions)

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

```{r}
summary(acie_context$type1)$table_values_amce
```


```{r mutate_context function}
mutate_context <- function(dat1, dat2, dat3, mod){
    d1 <- dat1 %>% 
        base_level(mod = mod) %>% 
        mutate(Context2 = "Interparty") 
    d2 <- dat2 %>% 
        base_level(mod = mod) %>% 
        mutate(Context2 = "IntrapartyD") 
    d3 <- dat3 %>% 
        base_level(mod = mod) %>% 
        mutate(Context2 = "IntrapartyR") 
    dd <- bind_rows(d1, d2, d3) %>% 
        mutate(Context2 = factor(Context2, levels = c("Interparty",
                                                      "IntrapartyD",
                                                      "IntrapartyR")))
    return(dd)
}
```

```{r df_acie_context1}
df_acie_context1 <- mutate_context(
    summary(acie_context$type1)$Context21amce,
    summary(acie_context$type1)$Context22amce,
    summary(acie_context$type1)$Context23amce,
    mod = acie_context$type1
    ) %>% 
    mutate(
        judge_lab = if_else(Context2 == "Interparty" &
                                Level == "Female",
                            "Judge's attributes", NA_character_),
        Context2 = str_c("Context = ", Context2)
        )
```


```{r pl_acie_context1, fig.width=10, fig.height=10}
pl_acie_context1 <- df_acie_context1 %>% 
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.13, .2),
                xlab = "Change in Pr(Self value influence judge)",
                facet_vari = "Context2",
                text_x = -.34, text_y = 26.7)

pl_acie_context1
```


```{r save Part9_c}
ggsave("output_figure/appendix/Part9_c.png", pl_acie_context1, width = 10, height = 10)
```


```{r df_acie_context2}
df_acie_context2 <- mutate_context(
    summary(acie_context$type2)$Context21amce,
    summary(acie_context$type2)$Context22amce,
    summary(acie_context$type2)$Context23amce,
    mod = acie_context$type2
    ) %>% 
    mutate(
        judge_lab = if_else(Context2 == "Interparty" &
                                Level == "Female",
                            "Judge's attributes", NA_character_),
        Context2 = str_c("Context = ", Context2)
        )
```


```{r pl_acie_context2, fig.width=10, fig.height=10}
pl_acie_context2 <- df_acie_context2 %>% 
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.13, .2),
                xlab = "Change in Pr(Biased judge)",
                facet_vari = "Context2",
                text_x = -.34, text_y = 26.7)

pl_acie_context2
```


```{r save Part9_d}
ggsave("output_figure/appendix/Part9_d.png", pl_acie_context2, width = 10, height = 10)
```

## Part 10: Gender affinity effects

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


```{r}
summary(acie_rsex$type1)$table_values_amce
```

```{r mutate_rsex function}
mutate_resex <- function(dat1, dat2, mod){
    d1 <- dat1 %>% 
        base_level(mod = mod) %>% 
        mutate(Rsex = "Female") 
    d2 <- dat2 %>% 
        base_level(mod = mod) %>% 
        mutate(Rsex = "Male")
    dd <- bind_rows(d1, d2) %>% 
        mutate(Rsex = factor(Rsex, levels = c("Female", "Male")))
    return(dd)
}
```

```{r df_acie_rsex}
df_acie_rsex1 <- mutate_resex(
    summary(acie_rsex$type1)$Rsex1amce,
    summary(acie_rsex$type1)$Rsex2amce,
    mod = acie_rsex$type1
    ) %>% 
    mutate(
        judge_lab = if_else(Rsex == "Female" & Level == "Female",
                            "Judge's attributes", NA_character_),
        Rsex = str_c("Respondent's\n Gender = ", Rsex),
        type = "(a) ACIE (personal values influence decisions)"
        )
df_acie_rsex2 <- mutate_resex(
    summary(acie_rsex$type2)$Rsex1amce,
    summary(acie_rsex$type2)$Rsex2amce,
    mod = acie_rsex$type2
    ) %>% 
    mutate(
        judge_lab = if_else(Level == "Female",
                            "Judge's attributes", NA_character_),
        Rsex = str_c("Respondent's\n Gender = ", Rsex),
        type = "(b) ACIE (judge is biased)"
        )
df_acie_rsex <- bind_rows(df_acie_rsex1, df_acie_rsex2)
```



```{r pl_acie_rsex, fig.width=14, fig.height=10}
pl_acie_rsex <- df_acie_rsex %>% 
  group_nest(type) %>% 
  mutate(
    gg = map(data, ~ ggplot(., aes(x = Estimate, y = Level,
                                   xmin = lwr, xmax = upr), color = "black") +
               facet_wrap(~ Rsex, ncol = 4) +
               geom_vline(xintercept = 0, size = .5, 
                          colour = "black", linetype = "dotted") +
               geom_pointrange() +
               coord_cartesian(ylim = c(1, 26.5),
                               xlim = c(-.15, .1), clip = 'off') +
               ylab(NULL) +
               theme(legend.position = "none",
                     axis.text = element_text(size = 11),
                     plot.margin = unit(c(1, 1, 0, 1), "lines"),
                     plot.title = element_text(size = 12, hjust = 0.5))),
    gg = map2(gg, type, ~ .x + labs(title = .y))
    )

pl_acie_rsex <- wrap_plots(pl_acie_rsex$gg) 
pl_acie_rsex[[1]] <- pl_acie_rsex[[1]] +
    geom_text(data = df_acie_rsex1,
              x = -.305, y = 26.7, hjust = 0, col = "black",
              size = 4,
              label = df_acie_rsex1$judge_lab, 
              show.legend = FALSE) +
    xlab("Change in Pr(Self value influence judge)")
pl_acie_rsex[[2]] <- pl_acie_rsex[[2]] + 
    xlab("Change in Pr(Biased judge)") +
    theme(axis.text.y = element_blank())

pl_acie_rsex
```

```{r save Part10}
ggsave("output_figure/appendix/Part10.png", pl_acie_rsex, width = 14, height = 10)
```

## Part 11: Race affinity effects

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


```{r}
summary(acie_rrace$type1)$table_values_amce
```

```{r mutate_rrace function}
mutate_rrace <- function(dat1, dat2, dat3, dat4,dat5, mod){
    d1 <- dat1 %>% 
        base_level(mod = mod) %>% 
        mutate(Rrace = "Asian") 
    d2 <- dat2 %>% 
        base_level(mod = mod) %>% 
        mutate(Rrace = "Black")
    d3 <- dat3 %>% 
        base_level(mod = mod) %>% 
        mutate(Rrace = "Hispanic")
    d4 <- dat4 %>% 
        base_level(mod = mod) %>% 
        mutate(Rrace = "Other")
    d5 <- dat5 %>% 
        base_level(mod = mod) %>% 
        mutate(Rrace = "White")
    dd <- bind_rows(d1, d2, d3, d4, d5) %>% 
        mutate(Rsex = factor(Rrace, levels = c("Asian", "Black", "Hispanic",
                                               "White", "Other")))
    return(dd)
}
```


```{r df_acie_rrace}
df_acie_rrace1 <- mutate_rrace(
    summary(acie_rrace$type1)$Rrace1amce,
    summary(acie_rrace$type1)$Rrace2amce,
    summary(acie_rrace$type1)$Rrace3amce,
    summary(acie_rrace$type1)$Rrace4amce,
    summary(acie_rrace$type1)$Rrace5amce,
    mod = acie_rrace$type1
    ) %>% 
    mutate(
        judge_lab = if_else(Rrace == "Asian" &
                                Level ==  "Female",
                            "Judge's attributes", NA_character_),
        Rrace = str_c("Respondent's\n Race = ", Rrace)
        )
df_acie_rrace2 <- mutate_rrace(
    summary(acie_rrace$type2)$Rrace1amce,
    summary(acie_rrace$type2)$Rrace2amce,
    summary(acie_rrace$type2)$Rrace3amce,
    summary(acie_rrace$type2)$Rrace4amce,
    summary(acie_rrace$type2)$Rrace5amce,
    mod = acie_rrace$type2
    ) %>% 
    mutate(
        judge_lab = if_else(Rrace == "Asian" &
                                Level ==  "Female",
                            "Judge's attributes", NA_character_),
        Rrace = str_c("Respondent's\n Race = ", Rrace)
        )
```


```{r pl_acie_rrace1, fig.width=13, fig.height=15}
pl_acie_rrace1 <- df_acie_rrace1 %>%
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.3, .3),
                xlab = "Change in Pr(Self value influence judge)",
                facet_vari = "Rrace",
                text_x = -.6, text_y = 27)

pl_acie_rrace1
```


```{r save Part11_a}
ggsave("output_figure/appendix/Part11_a.png", pl_acie_rrace1, width = 13, height = 15)
```


```{r pl_acie_rrace2, fig.width=13, fig.height=15}
pl_acie_rrace2 <- df_acie_rrace2 %>%
  conjoint_plot(ylim = c(1, 26.5), xlim = c(-.3, .3),
                xlab = "Change in Pr(Biased judge)",
                facet_vari = "Rrace",
                text_x = -.6, text_y = 27)

pl_acie_rrace2
```


```{r save Part11_b}
ggsave("output_figure/appendix/Part11_b.png", pl_acie_rrace2, width = 13, height = 15)
```


