---
title: 'Mediation: Empirical 2D Figures and Regressions'
author: "Alessandra Casella, Evan Friedman, Manuel Perez Archila"
date: "November 2020"
output: 
  pdf_document:
    fig_caption: yes
    number_sections: yes
---

```{r global_options, include=FALSE}
## This saves you from having to do this for every chunk
knitr::opts_chunk$set(echo = FALSE, 
                      warning = FALSE, 
                      message = FALSE)
```

```{r setup, include=FALSE}
library(ggplot2)
library(ggthemes)
library(boot)
library(data.table)
library(stargazer)
library(knitr)
library(lfe)
library(dplyr)
library(xlsx)
load("Mediation_Data.RData")
mediation.data <- as.data.table(mediation.data)
# Note Parameter 1 is q =1/2 and Parameter 0 is q =1/3
```

# Figures 

```{r honesty_f, include = FALSE}
# Clean and Reorganize Data
mediation.data[, Order := ifelse(Session <= 6, 1, 2) ]
messages.data <- mediation.data[Treatment != 4 , .(Parameter, Session, Order, Treatment, Period, ID = Player1SubjectID, Type = Player1Type, Message = Player1Message, Payoff = Player1Payoff)]
messages.data <-rbind(messages.data, mediation.data[Treatment != 4 , .(Parameter, Session, Order, Treatment, Period, ID = Player2SubjectID, Type = Player2Type, Message = Player2Message, Payoff = Player2Payoff)])
setkey(messages.data, Session, Period, ID)
messages.data[, ID := paste0(Session, "-", ID)]
messages.data$ID <- factor(messages.data$ID)
messages.data[, `:=`(HighType = as.numeric(Type == 1), LowType = as.numeric(Type == 2), HighMessage = as.numeric(Message == 1), LowMessage = as.numeric(Message == 2), SilenceMessage = as.numeric(Message == 3))]

# Define Function that plots Messages according to parameter or session (session overrides parameter)
plot.messages <- function(parameter = 1, order = NA, session = NA){
  
  # Create Data Frame that will hold final Values
  honesty <- data.frame(matrix(nrow = 0, ncol = 7))
  
  # Filter by parameter, order or session as needed
  if(is.na(session)) {
    if(is.na(order)){
      title_plot <- paste0("Messages sent by Type - Parameter ", parameter)
      messages <- messages.data[Parameter == parameter]
    }else{
      title_plot <- paste0("Messages sent by Type - Parameter ", parameter, " Order ", order)
      messages <- messages.data[Parameter == parameter & Order == order]
    }
  } else{
    title_plot <- paste0("Messages sent by Type - Session ", session)
    messages <- messages.data[Session == session]
  }   
  
  # For Each treatment, filter 
  for(treatment in 1:3){
    messages_treatment <- messages[Treatment == treatment]
    
    # Then calculate fixed effects linear models clustering by ID
    model_HighMessage <- felm(HighMessage ~ HighType + LowType + 0 | 0 | 0 | ID, 
                              data = messages_treatment) 
    model_LowMessage <- felm(LowMessage ~ HighType + LowType + 0 | 0 | 0 | ID, 
                             data = messages_treatment)
    model_SilenceMessage <- felm(SilenceMessage ~ HighType + LowType + 0 | 0 | 0 | ID, 
                                 data = messages_treatment)
    
    # Extract Values for each of the Type-Message Pairs and append them to the data frame with the values
    Hh <- list(parameter, treatment, "High", "high", coefficients(model_HighMessage)["HighType"],
               confint(model_HighMessage)[1,1], confint(model_HighMessage)[1,2])
    Hl <- list(parameter, treatment, "High", "low", coefficients(model_LowMessage)["HighType"],
               confint(model_LowMessage)[1,1], confint(model_LowMessage)[1,2])
    Hs <- list(parameter, treatment, "High", "silence", coefficients(model_SilenceMessage)["HighType"],
               confint(model_SilenceMessage)[1,1], confint(model_SilenceMessage)[1,2])
    Lh <- list(parameter, treatment, "Low", "high", coefficients(model_HighMessage)["LowType"],
               confint(model_HighMessage)[2,1], confint(model_HighMessage)[2,2])
    Ll <- list(parameter, treatment, "Low", "low", coefficients(model_LowMessage)["LowType"],
               confint(model_LowMessage)[2,1], confint(model_LowMessage)[2,2])
    Ls <- list(parameter, treatment, "Low", "silence", coefficients(model_SilenceMessage)["LowType"],
               confint(model_SilenceMessage)[2,1], confint(model_SilenceMessage)[2,2])
    
    honesty <- rbind(honesty, Hh, Hl, Hs, Lh, Ll, Ls)
  }

  # Rename Columns
  colnames(honesty) <- c("Parameter", "Treatment", "Type", "Message", "Value", "Lower_CI", "Upper_CI")
  
  #Plot
  dodge <- position_dodge(width = 0.9)
  p <- ggplot(data = honesty, aes(x = factor(Treatment), y = Value, fill = Message))
  p <- p + geom_bar(stat = "identity", position = dodge) + facet_wrap(~Type) +
    geom_errorbar(aes(ymin = Lower_CI, ymax = Upper_CI), position = dodge, width = 0.25) +
    scale_fill_discrete(name = "Message") +
    labs(x = "Treatment", y = "Relative Frequency") +
    ggtitle(title_plot) +
    scale_x_discrete(name="Treatment", breaks = c("1", "2", "3"), labels = c("UC", "HM", "CM")) + 
    scale_y_continuous(limits=c(0, 1.0)) +
    theme_classic()+ 
    theme(strip.text.x = element_text(size = 16), axis.text=element_text(size=16),
        axis.title=element_text(size=16), plot.title = element_text(size = 18,face="bold"),legend.title=element_text(size=16), 
    legend.text=element_text(size=14))
  
  print(p)
}
```

```{r peace_f, include = FALSE}
# Clean and Reorganize Peace Data
peace.data <- mediation.data[, .(Parameter, Session, Order, Treatment, Period, Player1SubjectID, Player2SubjectID, Player1Type, Player2Type, Player1Message, Player2Message, Outcome)]
peace.data[, `:=`(Player1ID = paste0(Session, "-", Player1SubjectID), Player2ID = paste0(Session, "-", Player2SubjectID))]
peace.data$Player1ID <- factor(peace.data$Player1ID)
peace.data$Player2ID <- factor(peace.data$Player2ID)
peace.data[, `:=`(PairID = paste0(Session, "-", pmin(Player1SubjectID, Player2SubjectID), "-", pmax(Player1SubjectID, Player2SubjectID)))]
peace.data$PairID <- factor(peace.data$PairID)
peace.data[, `:=`(IsPeace = as.numeric(Outcome == 1), IsWar = as.numeric(Outcome == 2), NC = as.numeric(Treatment == 4), UC = as.numeric(Treatment == 1), HM = as.numeric(Treatment == 2), CM = as.numeric(Treatment == 3))]

# No NC
plot.peace <- function(parameter = 1, order = NA, session = NA, cluster = NA){
  
  # Filter by parameter, order or session as needed
  if(is.na(session)) {
    if(is.na(order)){
      title_plot <- paste0("Peace Frequency - Parameter ", parameter)
      peace_ref <- peace.data[Parameter == parameter & NC != 1]
    }else{
      title_plot <- paste0("Parameter ", parameter, " Order ", order, " (all sessions)")
      peace_ref <- peace.data[Parameter == parameter & Order == order & NC != 1]
    }
  } else{
    title_plot <- paste0("Session ", session)
    peace_ref <- peace.data[Session == session & NC != 1]
  }
  
  if(is.na(cluster)){
    lin_model <- felm(IsPeace ~  UC + HM + CM + 0 | 0 | 0 | 0, data = peace_ref)
  } else if(cluster == "session"){
    lin_model <- felm(IsPeace ~  UC + HM + CM + 0 | 0 | 0 | Session, data = peace_ref)
  } else if(cluster == "pair"){
    lin_model <- felm(IsPeace ~  UC + HM + CM + 0 | 0 | 0 | PairID, data = peace_ref)
  }
  
  results <- as.data.frame(100 * confint(lin_model))
  
  results$Value <- 100 * coefficients(lin_model)
  results$Treatment <- factor(c("UC", "HM", "CM"), levels = c("UC", "HM", "CM"))
  
  colnames(results) <- c("Lower_CI", "Upper_CI", "Value", "Treatment")

  #print(results)
  
  #Plot
  dodge <- position_dodge(width = 0.9)
  p <- ggplot(data = results, aes(x = Treatment, y = Value))
  p <- p + geom_bar(stat = "identity", position = dodge, fill = "darkgreen") +
    geom_errorbar(aes(ymin = Lower_CI, ymax = Upper_CI), position = dodge, width = 0.25) +
    labs(x = "Treatment", y = "Relative Frequency (%)") +
    ggtitle(title_plot) +
    scale_y_continuous(limits=c(0, 100))+
    theme_classic()+ 
    theme(strip.text.x = element_text(size = 16), axis.text=element_text(size=16),
        axis.title=element_text(size=16), plot.title = element_text(size = 18,face="bold"),legend.title=element_text(size=16), 
    legend.text=element_text(size=14))
  return(p)
  
}
```

```{r}
plot.peace.nc <- function(parameter = 1, cluster = NA){
  
  title_plot <- paste0("NC and UC Peace Frequency - Parameter ", parameter)
  peace_ref <- peace.data[Parameter == parameter & (NC == 1 | UC ==1)]

  if(is.na(cluster)){
    lin_model <- felm(IsPeace ~  NC + UC + 0 | 0 | 0 | 0, data = peace_ref)
  } else if(cluster == "session"){
    lin_model <- felm(IsPeace ~  NC + UC + 0 | 0 | 0 | Session, data = peace_ref)
  } else if(cluster == "pair"){
    lin_model <- felm(IsPeace ~  NC + UC + 0 | 0 | 0 | PairID, data = peace_ref)
  }
  
  results <- as.data.frame(100 * confint(lin_model))
  
  results$Value <- 100 * coefficients(lin_model)
  results$Treatment <- factor(c("NC", "UC"), levels = c("NC", "UC"))
  
  colnames(results) <- c("Lower_CI", "Upper_CI", "Value", "Treatment")

  #print(results)
  
  #Plot
  dodge <- position_dodge(width = 0.9)
  p <- ggplot(data = results, aes(x = Treatment, y = Value))
  p <- p + geom_bar(stat = "identity", position = dodge, fill = "darkgreen") +
    geom_errorbar(aes(ymin = Lower_CI, ymax = Upper_CI), position = dodge, width = 0.25) +
    labs(x = "Treatment", y = "Relative Frequency (%)") +
    ggtitle(title_plot) +
    scale_y_continuous(limits=c(0, 100))+
    theme_classic()+ 
    theme(strip.text.x = element_text(size = 16), axis.text=element_text(size=16),
        axis.title=element_text(size=16), plot.title = element_text(size = 18,face="bold"),legend.title=element_text(size=16), 
    legend.text=element_text(size=14))
  return(p)
  
}

```


```{r}
info.data <- as.data.table(read.xlsx("/Users/manuel/Desktop/Analysis and Notes - Manuel/Data Analysis and Notes/Data Analysis/Information Measures Session - Rev.xlsx", 1))

info.data.par <- info.data[, lapply(.SD, mean), keyby = .(Parameter,Treatment), .SDcols = c("ih", "Kh", "il", "Kl")]

long.info <- melt(info.data, id = 1:5)

long.info.par <- melt(info.data.par, id = 1:2)

plot.info <- function(parameter = 1, measure = "index"){
  if(measure == "index"){
    data <- long.info[Parameter == parameter & (variable == "ih" | variable == "il"), .(Session, Treatment, variable, value)]
    title <- paste("Information Measure - Parameter", parameter)
  }
  if(measure == "KL"){
    data <- long.info[Parameter == parameter & (variable == "Kh" | variable == "Kl"), .(Session, Treatment, variable, value)]
    title <- paste("Kullback Leibler Measure - Parameter", parameter)
  }
  
p <- ggplot(data = data, aes(x = factor(Session), y = value, fill = Treatment))+ geom_bar(stat = "identity", position = position_dodge(width = 0.9)) + facet_wrap(~factor(variable)) +
    labs(x = "Session", y = "Information Measure") + 
    scale_y_continuous(limits=c(0, 1.0))+
    ggtitle(title) + theme(classic)

print(p)
  
  }

plot.info.par <- function(parameter = 1, measure = "index"){
  if(measure == "index"){
    data <- long.info.par[Parameter == parameter & (variable == "ih" | variable == "il"), .(Treatment, variable, value)]
    title <- paste("Information Measure - Parameter", parameter)
  }
  if(measure == "KL"){
    data <- long.info.par[Parameter == parameter & (variable == "Kh" | variable == "Kl"), .(Treatment, variable, value)]
    data[, variable := ifelse(variable == "Kh", "KL(h)", "KL(l)")]
    title <- paste("Kullback Leibler Measure - Parameter", parameter)
  }
  
data$Treatment <- factor(data$Treatment, levels = c("UC", "HM", "CM"))
  
p <- ggplot(data = data, aes(x = Treatment, y = value))+ geom_bar(stat = "identity", position = position_dodge(width = 0.9), fill="#FFBF00") + facet_wrap(~variable)+
    labs(x = "Treatment", y = "Information Measure") + 
    scale_y_continuous(limits=c(0, 1.0))+
    ggtitle(title)+theme_classic()+ 
    theme(strip.text.x = element_text(size = 16), axis.text=element_text(size=16),
        axis.title=element_text(size=16), plot.title = element_text(size = 18,face="bold"),legend.title=element_text(size=16), 
    legend.text=element_text(size=14))

print(p)
  
  }

```


```{r}
plot.acceptances <- function(parameter = 1, treatment = 3){
  
  data <- rbind(mediation.data[Parameter == parameter & Treatment == treatment, .(Type = Player1Type, Recommendation = Player1MediatorRecommendation, Acceptance = Player1AcceptRecommendation)], mediation.data[Parameter == parameter & Treatment == treatment, .(Type = Player2Type, Recommendation = Player2MediatorRecommendation, Acceptance = Player2AcceptRecommendation)])
  
  data[, `:=`(Type = ifelse(Type == 1, "High", "Low"), Recommendation = ifelse(Recommendation <= 0.31 & Recommendation >=0.29, "30", ifelse(Recommendation ==0.5, "50", ifelse(Recommendation == 0.7, "70", "Walk Out"))), Acceptance =factor( ifelse(Acceptance == 1, "Accept", ifelse(Acceptance == 0, "Reject", "Mediator Walk Out"))))]
  
  
  
  rejections <- unique(data[Acceptance != "Accept", .(.N, Acceptance), keyby = .(Type, Recommendation)])
  
  if(nrow(rejections[Recommendation == "70"]) ==0){
    rejections <- rbind(rejections, data.table(Type = c("High", "Low"), Recommendation = c("70", "70"), N = c(0,0), Acceptance = c("Reject", "Reject")))
  }
  
  rejections[Acceptance == "Mediator Walk Out" & Type == "High", `:=`(N = sum(rejections[Acceptance =="Mediator Walk Out", N])/2, Type = "Actual")]

    #rejections <- rejections[Acceptance != "Mediator Walk Out" | Type != "Low"]

  t = ifelse(parameter == 0, 6 * 120 * 2/9, 6 * 120 * 1/8)
  
  rejections[Acceptance == "Mediator Walk Out" & Type == "Low", `:=`(N = t, Type = "If Sincere")]
  
  rejections[, Type := factor(Type, levels = c("High", "Low", "Actual", "If Sincere"))]
  
  
  p <- ggplot(rejections, aes(x = factor(Recommendation), y = N , fill = Type)) + geom_bar(stat = "identity", position = position_dodge2(width = 0.9, preserve = "single")) +
   labs(x = "Recommendation", y = "Absolute Frequency in the Data", fill = NULL) + 
    ggtitle(paste0("Number of Rejections and Refusals - Parameter ", parameter, ", ", ifelse(treatment == 3, "CM", "HM")))+ylim(0,250)+
    theme_classic() +scale_fill_manual(values=c("#228B22",  "#1D3CD6", "#FFA500", "#FF6600"))+ 
    theme(strip.text.x = element_text(size = 14), axis.text=element_text(size=14),
        axis.title=element_text(size=14), plot.title = element_text(size = 15,face="bold"),legend.title=element_text(size=14), 
    legend.text=element_text(size=13))
  print(p)
}
```

## Honesty

```{r honesty_graphs}
plot.messages(parameter = 0)
plot.messages(parameter = 1)
```

## Peace

```{r peace_graphs}
print(plot.peace(parameter = 0, cluster = "pair"))
print(plot.peace(parameter = 1, cluster = "pair"))
```

## Causes of War - Computer Mediation 
```{r causes_of_war}
plot.acceptances(1, 3)
plot.acceptances(0, 3)
```


# Appendix Figures

## Information Measure

```{r information}
plot.info.par(measure = "KL")
plot.info.par(0, measure = "KL")
```


```{r}
# Define Function that plots Messages according to parameter or session (session overrides parameter)
plot.messages.2nd <- function(parameter = 1, order = NA, session = NA){
  
  # Create Data Frame that will hold final Values
  honesty <- data.frame(matrix(nrow = 0, ncol = 7))
  
  # Filter by parameter, order or session as needed
  if(is.na(session)) {
    if(is.na(order)){
      title_plot <- paste0("Messages - Param ", parameter, " (2nd Treatment Position)")
      messages <- messages.data[Parameter == parameter & ((Treatment == 1 & Order == 1)|(Treatment == 3 & Order == 2))]
    }else{
      title_plot <- paste0("Messages sent by Type - Parameter ", parameter, " Order ", order)
      messages <- messages.data[Parameter == parameter & Order == order]
    }
  } else{
    title_plot <- paste0("Messages sent by Type - Session ", session)
    messages <- messages.data[Session == session]
  }   
  
  # For Each treatment, filter 
  for(treatment in c(1,3)){
    messages_treatment <- messages[Treatment == treatment]
    
    # Then calculate fixed effects linear models clustering by ID
    model_HighMessage <- felm(HighMessage ~ HighType + LowType + 0 | 0 | 0 | ID, 
                              data = messages_treatment) 
    model_LowMessage <- felm(LowMessage ~ HighType + LowType + 0 | 0 | 0 | ID, 
                             data = messages_treatment)
    model_SilenceMessage <- felm(SilenceMessage ~ HighType + LowType + 0 | 0 | 0 | ID, 
                                 data = messages_treatment)
    
    # Extract Values for each of the Type-Message Pairs and append them to the data frame with the values
    Hh <- list(parameter, treatment, "High", "high", coefficients(model_HighMessage)["HighType"],
               confint(model_HighMessage)[1,1], confint(model_HighMessage)[1,2])
    Hl <- list(parameter, treatment, "High", "low", coefficients(model_LowMessage)["HighType"],
               confint(model_LowMessage)[1,1], confint(model_LowMessage)[1,2])
    Hs <- list(parameter, treatment, "High", "silence", coefficients(model_SilenceMessage)["HighType"],
               confint(model_SilenceMessage)[1,1], confint(model_SilenceMessage)[1,2])
    Lh <- list(parameter, treatment, "Low", "high", coefficients(model_HighMessage)["LowType"],
               confint(model_HighMessage)[2,1], confint(model_HighMessage)[2,2])
    Ll <- list(parameter, treatment, "Low", "low", coefficients(model_LowMessage)["LowType"],
               confint(model_LowMessage)[2,1], confint(model_LowMessage)[2,2])
    Ls <- list(parameter, treatment, "Low", "silence", coefficients(model_SilenceMessage)["LowType"],
               confint(model_SilenceMessage)[2,1], confint(model_SilenceMessage)[2,2])
    
    honesty <- rbind(honesty, Hh, Hl, Hs, Lh, Ll, Ls)
  }

  # Rename Columns
  colnames(honesty) <- c("Parameter", "Treatment", "Type", "Message", "Value", "Lower_CI", "Upper_CI")
  
  honesty$Lower_CI <- pmax(0, honesty$Lower_CI)
  
  #Plot
  dodge <- position_dodge(width = 0.9)
  p <- ggplot(data = honesty, aes(x = factor(Treatment), y = Value, fill = Message))
  p <- p + geom_bar(stat = "identity", position = dodge) + facet_wrap(~Type) +
    geom_errorbar(aes(ymin = Lower_CI, ymax = Upper_CI), position = dodge, width = 0.25) +
    scale_fill_discrete(name = "Message") +
    labs(x = "Treatment", y = "Relative Frequency") +
    ggtitle(title_plot) +
    scale_x_discrete(name="Treatment", breaks = c("1", "2", "3"), labels = c("UC", "HM", "CM")) + 
    scale_y_continuous(limits=c(0, 1.0)) +
    theme_classic()+ 
    theme(strip.text.x = element_text(size = 16), axis.text=element_text(size=16),
        axis.title=element_text(size=16), plot.title = element_text(size = 18,face="bold"),legend.title=element_text(size=16), 
    legend.text=element_text(size=14))
  
  print(p)
}
```

```{r, include = FALSE}
# Clean and Reorganize Peace Data

# No NC
plot.peace.2nd <- function(parameter = 1, order = NA, session = NA, cluster = NA){
  
  # Filter by parameter, order or session as needed
  if(is.na(session)) {
    if(is.na(order)){
      title_plot <- paste0("Peace - Param ", parameter, " (2nd Treatment Position)")
      peace_ref <- peace.data[Parameter == parameter & ((Treatment == 1 & Order == 1)|(Treatment == 3 & Order == 2))]
    }else{
      title_plot <- paste0("Parameter ", parameter, " Order ", order, " (all sessions)")
      peace_ref <- peace.data[Parameter == parameter & Order == order & NC != 1]
    }
  } else{
    title_plot <- paste0("Session ", session)
    peace_ref <- peace.data[Session == session & NC != 1]
  }
  
  if(is.na(cluster)){
    lin_model <- felm(IsPeace ~  UC + CM + 0 | 0 | 0 | 0, data = peace_ref)
  } else if(cluster == "session"){
    lin_model <- felm(IsPeace ~  UC + CM + 0 | 0 | 0 | Session, data = peace_ref)
  } else if(cluster == "pair"){
    lin_model <- felm(IsPeace ~  UC + CM + 0 | 0 | 0 | PairID, data = peace_ref)
  }
  
  results <- as.data.frame(100 * confint(lin_model))
  
  results$Value <- 100 * coefficients(lin_model)
  results$Treatment <- factor(c("UC", "CM"), levels = c("UC", "CM"))
  
  colnames(results) <- c("Lower_CI", "Upper_CI", "Value", "Treatment")

  #print(results)
  
  #Plot
dodge <- position_dodge(width = 0.9)
  p <- ggplot(data = results, aes(x = Treatment, y = Value))
  p <- p + geom_bar(stat = "identity", position = dodge, fill = "darkgreen") +
    geom_errorbar(aes(ymin = Lower_CI, ymax = Upper_CI), position = dodge, width = 0.25) +
    labs(x = "Treatment", y = "Relative Frequency (%)") +
    ggtitle(title_plot) +
    scale_y_continuous(limits=c(0, 100))+
    theme_classic()+ 
    theme(strip.text.x = element_text(size = 16), axis.text=element_text(size=16),
        axis.title=element_text(size=16), plot.title = element_text(size = 18,face="bold"),legend.title=element_text(size=16), 
    legend.text=element_text(size=14))
  return(p)
}
```

## Honesty

```{r}
plot.messages.2nd(parameter = 0)
plot.messages.2nd(parameter = 1)
```

## Peace

```{r}
print(plot.peace.2nd(parameter = 0, cluster = "pair"))
print(plot.peace.2nd(parameter = 1, cluster = "pair"))
```

# Regressions

```{r, include = FALSE}
mediation.data <- as.data.table(mediation.data)
mediation.data[, Player1Message := ifelse(Player1Message == -1, NA, ifelse(Player1Message == 1, "High", ifelse(Player1Message == 2, "Low", "Silence")))]
mediation.data[, Player2Message := ifelse(Player2Message == -1, NA, ifelse(Player2Message == 1, "High", ifelse(Player2Message == 2, "Low", "Silence")))]
mediation.data[, Player1Type := ifelse(Player1Type == 1, "High", "Low")]
mediation.data[, Player2Type := ifelse(Player2Type == 1, "High", "Low")]
mediation.data[, Treatment := ifelse(Treatment == 4, "NC", ifelse(Treatment == 3, "CM", ifelse(Treatment == 2, "HM", "UC")))]
mediation.data[, Player1MediatorRecommendation := ifelse(Treatment == "NC" | Treatment == "UC", NA, ifelse(Player1MediatorRecommendation == -1, "W", as.character(round(100 * Player1MediatorRecommendation))))]
mediation.data[, Player2MediatorRecommendation := ifelse(Treatment == "UC" | Treatment == "NC", NA, ifelse(Player2MediatorRecommendation == -1, "W", as.character(round(100 * Player2MediatorRecommendation))))]
mediation.data[, c("Parameter", "Order", "Session", "Treatment") := list(factor(Parameter), factor(Order), factor(Session), factor(Treatment, levels = c("UC", "HM", "CM", "NC")))]
rm(list=setdiff(ls(), "mediation.data"))
```


```{r, include = FALSE}
# Clean and Reorganize Messages Data
messages.data <- mediation.data[Treatment !=  "NC", .(Parameter, Session, Order, Treatment, Period, ID = Player1SubjectID, Type = Player1Type, Message = Player1Message, Recommendation = Player1MediatorRecommendation, Rejection = 1 - Player1AcceptRecommendation, Payoff = Player1Payoff)]
messages.data <-rbind(messages.data, mediation.data[Treatment != "NC" , .(Parameter, Session, Order, Treatment, Period, ID = Player2SubjectID, Type = Player2Type, Message = Player2Message, Recommendation = Player2MediatorRecommendation, Rejection = 1 - Player2AcceptRecommendation, Payoff = Player2Payoff)])
setkey(messages.data, Session, Period, ID)
messages.data[, ID := paste0(Session, "-", ID)]
messages.data$ID <- factor(messages.data$ID)
messages.data[, IsHonest := ifelse(Message == Type, 1, 0)]
messages.data[, IsSilent := ifelse(Message == "Silence", 1, 0)]
messages.data[, TreatmentPosition := ifelse(Period > 30 & Period < 61, 2, ifelse(Period > 60, 3, 1)) ]
```


```{r, include = FALSE}
# # Clean and Reorganize Peace Data
peace.data <- mediation.data[Treatment != "NC", .(Parameter, Session, Order, Treatment, Period, Player1SubjectID, Player2SubjectID, Player1Type, Player2Type, Player1Message, Player2Message, Outcome)]
peace.data[, `:=`(Player1ID = paste0(Session, "-", Player1SubjectID), Player2ID = paste0(Session, "-", Player2SubjectID))]
peace.data$Player1ID <- factor(peace.data$Player1ID)
peace.data$Player2ID <- factor(peace.data$Player2ID)
peace.data[, `:=`(PairID = paste0(Session, "-", pmin(Player1SubjectID, Player2SubjectID), "-", pmax(Player1SubjectID, Player2SubjectID)))]
peace.data$PairID <- factor(peace.data$PairID)
peace.data[, `:=`(PairType = paste0(pmin(Player1Type, Player2Type), "-", pmax(Player1Type, Player2Type)))]
peace.data[, `:=`(PairType.f = factor(PairType))]
peace.data[, `:=`(IsPeace = as.numeric(Outcome == 1))]
peace.data[, TreatmentPosition := ifelse(Period > 30 & Period < 61, 2, ifelse(Period > 60, 3, 1)) ]
```


```{r}
sincerity.linear.model.1 <- felm(IsHonest ~ Treatment + Order + 
                       Parameter + Type + Period + Treatment*Type +
                       Order*Type + Parameter*Type + Period*Type | 0 | 0 | ID,
                       data = messages.data)
summary(sincerity.linear.model.1)
```

```{r}
silence.linear.model.1 <- felm(IsSilent ~ Treatment + Order + 
                       Parameter + Type + Period + Treatment*Type +
                       Order*Type + Parameter*Type + Period*Type | 0 | 0 | ID,
                       data = messages.data)
summary(silence.linear.model.1)
```



```{r}
peace.linear.model.1 <- felm(IsPeace ~ Treatment + Order + 
                       Parameter + Period | 0 | 0 | PairID,
                       data = peace.data)
summary(peace.linear.model.1)
```


```{r}
peace.linear.model.2 <- felm(IsPeace ~ Treatment + Order + 
                       Parameter + PairType + Period | 0 | 0 | PairID,
                       data = peace.data)
summary(peace.linear.model.2)
```

```{r}
peace.linear.model.3 <- felm(IsPeace ~ Treatment + Order + 
                       Parameter + PairType + Period + Treatment * PairType + Order * PairType + Parameter * PairType  + Period * PairType | 0 | 0 | PairID,
                       data = peace.data)
summary(peace.linear.model.3)
```


```{r}
peace.linear.model.1_UC <- felm(IsPeace ~ Order + 
                       Parameter + Period | 0 | 0 | PairID,
                       data = peace.data[Treatment == "UC"])
summary(peace.linear.model.1_UC)
```

```{r}
peace.linear.model.1_HM <- felm(IsPeace ~ Order + 
                       Parameter + Period | 0 | 0 | PairID,
                       data = peace.data[Treatment == "HM"])
summary(peace.linear.model.1_HM)
```

```{r}
peace.linear.model.1_CM <- felm(IsPeace ~ Order + 
                       Parameter + Period | 0 | 0 | PairID,
                       data = peace.data[Treatment == "CM"])
summary(peace.linear.model.1_CM)
```
