setwd("C:/Users/srish/Documents/ASP Thesis")
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.1     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.1     
## ── 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(ggplot2)
library(car)
## Loading required package: carData
## 
## Attaching package: 'car'
## 
## The following object is masked from 'package:dplyr':
## 
##     recode
## 
## The following object is masked from 'package:purrr':
## 
##     some
library(dunn.test)
library(WRS2)
library(stargazer)
## 
## Please cite as: 
## 
##  Hlavac, Marek (2022). stargazer: Well-Formatted Regression and Summary Statistics Tables.
##  R package version 5.2.3. https://CRAN.R-project.org/package=stargazer
## cleaning the data
ds<-read.csv("merged.csv")
ds$state <- trimws(ds$state, which = "right")
ds$state_party <- trimws(ds$state_party, which = "right")
ds$central_party <- trimws(ds$central_party, which = "right")
ds$pr[is.na(ds$pr)] = 0
ds$scaled[is.na(ds$scaled)] = 4
## creating misalign due to data entry error
ds<-ds%>%
  filter(X_merge == "Matched (3)")%>%
  mutate(misalign = case_when(
    scaled == 3 ~ 0,
    scaled == 4 ~ 0,
    scaled == 1 ~ 1,
    scaled == 2 ~ 1, 
  ))
#### analysing one sided violence by the central govt against only civilians 
state_only<- ds%>%
  filter(type_of_violence == 3 & side_a == "Government of India")

view(state_only)
table(state_only$type_of_violence)
## 
##  3 
## 21
table(state_only$misalign)
## 
##  0  1 
##  9 12
table(state_only$scaled)
## 
## 1 2 4 
## 6 6 9
table(state_only$central_party)
## 
## INC NDA  NF UPA 
##   1   9   2   9
table(state_only$state_party)
## 
##   AITC    BJP CPI(M)    INC    JMM    NPF    SAD    TDP VACANT  YSRCP 
##      2      2      4      7      1      1      1      1      1      1
table(state_only$side_a)
## 
## Government of India 
##                  21
table(state_only$side_b)
## 
## Civilians 
##        21
table(state_only$State)
## 
## Andhra Pradesh          Assam          Bihar      Jharkhand        Manipur 
##              2              3              1              2              1 
##      Meghalaya       Nagaland         Punjab        Tripura    West Bengal 
##              1              2              1              4              4
table(state_only$pr)
## 
##  0  1 
## 20  1
##misalignment and pr occurences
contingency_table <- state_only%>%
  count(pr, misalign) %>%
  group_by(misalign) %>%
  mutate(proportion = n / sum(n)) %>%
  ungroup()

# Display the table
print(contingency_table)
## # A tibble: 3 × 4
##      pr misalign     n proportion
##   <dbl>    <dbl> <int>      <dbl>
## 1     0        0     8      0.889
## 2     0        1    12      1    
## 3     1        0     1      0.111
ggplot(contingency_table, aes(x = factor(misalign), y = proportion, fill = factor(pr))) +
  geom_bar(stat = "identity", position = position_dodge()) +
  labs(title = "Proportion of PR by Alignment",
       x = "Alignment",
       y = "Proportion",
       fill = "PR") +
  geom_text(aes(label = scales::percent(proportion), y = proportion + 0.02),
            position = position_dodge(width = 0.9),
            vjust = 0,
            color = "black") +
  theme_minimal()

##misalignemnt and afspa
contingency_table_afspa <- state_only%>%
  count(afspa, misalign) %>%
  group_by(misalign) %>%
  mutate(proportion = n / sum(n)) %>%
  ungroup()

# Display the table
print(contingency_table_afspa)
## # A tibble: 4 × 4
##   afspa misalign     n proportion
##   <int>    <dbl> <int>      <dbl>
## 1     0        0     3     0.333 
## 2     0        1    11     0.917 
## 3     1        0     6     0.667 
## 4     1        1     1     0.0833
ggplot(contingency_table_afspa, aes(x = factor(misalign), y = proportion, fill = factor(afspa))) +
  geom_bar(stat = "identity", position = position_dodge()) +
  labs(title = "Proportion of PR by Alignment",
       x = "misalignment",
       y = "Proportion",
       fill = "afspa") +
  geom_text(aes(label = scales::percent(proportion), y = proportion + 0.02),
            position = position_dodge(width = 0.9),
            vjust = 0,
            color = "black") +
  theme_minimal()

##summary stats 
get_mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}
mis_stats <- state_only %>%
  summarise(
    Mean = mean(misalign, na.rm = TRUE),
    Median = median(misalign, na.rm = TRUE),
    Mode = get_mode(misalign),
    Standard_Deviation = sd(misalign, na.rm = TRUE)
  )
print(mis_stats)
##        Mean Median Mode Standard_Deviation
## 1 0.5714286      1    1          0.5070926
scaled_stats <- state_only %>%
  summarise(
    Mean = mean(scaled, na.rm = TRUE),
    Median = median(scaled, na.rm = TRUE),
    Mode = get_mode(scaled),
    Standard_Deviation = sd(scaled, na.rm = TRUE)
  )
print(scaled_stats)
##       Mean Median Mode Standard_Deviation
## 1 2.571429      2    4           1.325573
pr_stats <- state_only %>%
  summarise(
    Mean = mean(pr, na.rm = TRUE),
    Median = median(pr, na.rm = TRUE),
    Mode = get_mode(pr),
    Standard_Deviation = sd(pr, na.rm = TRUE)
  )
print(pr_stats)
##         Mean Median Mode Standard_Deviation
## 1 0.04761905      0    0          0.2182179
## sum states of misaligned and fatalities
misal_stats <-state_only %>%
  group_by(misalign) %>%
  summarise(
    Mean_Death = mean(best_est, na.rm = TRUE),  # Calculate mean, remove NA values if any
    SD_Death = sd(best_est, na.rm = TRUE)       # Calculate standard deviation
  )
print(misal_stats)
## # A tibble: 2 × 3
##   misalign Mean_Death SD_Death
##      <dbl>      <dbl>    <dbl>
## 1        0       1.89     2.52
## 2        1       1.5      1.73
summary_afspa <-state_only %>%
  group_by(afspa) %>%
  summarise(
    Mean_Death = mean(best_est, na.rm = TRUE),  # Calculate mean, remove NA values if any
    SD_Death = sd(best_est, na.rm = TRUE)       # Calculate standard deviation
  )
print(summary_afspa)
## # A tibble: 2 × 3
##   afspa Mean_Death SD_Death
##   <int>      <dbl>    <dbl>
## 1     0       1.93     2.37
## 2     1       1.14     1.21
summary_state <-state_only %>%
  group_by(State) %>%
  summarise(
    Mean_Death = mean(best_est, na.rm = TRUE),  # Calculate mean, remove NA values if any
    SD_Death = sd(best_est, na.rm = TRUE)       # Calculate standard deviation
  )
print(summary_state)
## # A tibble: 10 × 3
##    State          Mean_Death SD_Death
##    <chr>               <dbl>    <dbl>
##  1 Andhra Pradesh       1        0   
##  2 Assam                1        1   
##  3 Bihar                0       NA   
##  4 Jharkhand            2        1.41
##  5 Manipur              2       NA   
##  6 Meghalaya            0       NA   
##  7 Nagaland             5.5      3.54
##  8 Punjab               1       NA   
##  9 Tripura              1.75     2.87
## 10 West Bengal          1.25     1.26
## Difference in medians test 
ww_test_result <- wilcox.test(best_est ~ misalign, data = state_only, exact = FALSE)
print(ww_test_result) 
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  best_est by misalign
## W = 56.5, p-value = 0.8822
## alternative hypothesis: true location shift is not equal to 0
prs_test_result <- wilcox.test(best_est ~ pr, data = state_only, exact = FALSE)
print(prs_test_result)
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  best_est by pr
## W = 17.5, p-value = 0.228
## alternative hypothesis: true location shift is not equal to 0
afspa_test_result <- wilcox.test(best_est ~ afspa, data = state_only, exact = FALSE)
print(afspa_test_result)
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  best_est by afspa
## W = 56, p-value = 0.6131
## alternative hypothesis: true location shift is not equal to 0
## difference in medians removing high outliers  
filtered_state <- state_only %>%  
  filter(best_est <= quantile(best_est, 0.95))  # Remove high outliers, keeping up to the 95th percentile

ggplot(filtered_state, aes(x = factor(misalign), y = best_est, fill = factor(misalign))) +
  geom_boxplot(outlier.shape = NA) +  # Boxplot to show medians and distributions
  labs(title = "Fatality Rates by Alignment",
       x = "Alignment",
       y = "Fatality Rates") +
  theme_minimal() +
  geom_jitter(width = 0.2, alpha = 0.5, color = "black")

nation<- lm(state_only$misalign ~ state_only$best_est + state_only$State + state_only$pr + state_only$afspa)
summary(nation)
## 
## Call:
## lm(formula = state_only$misalign ~ state_only$best_est + state_only$State + 
##     state_only$pr + state_only$afspa)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.46830 -0.02536  0.00000  0.02536  0.46830 
## 
## Coefficients: (1 not defined because of singularities)
##                               Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                  9.683e-01  1.663e-01   5.822 0.000253 ***
## state_only$best_est          3.170e-02  4.061e-02   0.780 0.455149    
## state_only$StateAssam       -1.108e+00  3.226e-01  -3.434 0.007459 ** 
## state_only$StateBihar       -9.683e-01  2.823e-01  -3.430 0.007509 ** 
## state_only$StateJharkhand   -5.317e-01  2.317e-01  -2.295 0.047401 *  
## state_only$StateManipur     -1.139e+00  3.894e-01  -2.926 0.016854 *  
## state_only$StateMeghalaya   -1.076e+00  3.594e-01  -2.994 0.015103 *  
## state_only$StateNagaland    -1.197e+00  3.547e-01  -3.373 0.008218 ** 
## state_only$StatePunjab      -6.961e-16  2.794e-01   0.000 1.000000    
## state_only$StateTripura     -5.071e-02  2.141e-01  -0.237 0.818084    
## state_only$StateWest Bengal -7.924e-03  1.978e-01  -0.040 0.968921    
## state_only$pr                       NA         NA      NA       NA    
## state_only$afspa             1.078e-01  2.464e-01   0.437 0.672106    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.2281 on 9 degrees of freedom
## Multiple R-squared:  0.9089, Adjusted R-squared:  0.7976 
## F-statistic: 8.167 on 11 and 9 DF,  p-value: 0.001943
## insignificant results 
##################################################################
state_actor<-ds%>%
  filter(type_of_violence == 1)

# Perform a Mann-Whitney U test
mw_test_result <- wilcox.test(best_est ~ misalign, data = state_actor, exact = FALSE)
print(mw_test_result)
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  best_est by misalign
## W = 980087, p-value = 0.005363
## alternative hypothesis: true location shift is not equal to 0
afspa_test_result <- wilcox.test(best_est ~ afspa, data = state_actor, exact = FALSE)
print(afspa_test_result)
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  best_est by afspa
## W = 1007784, p-value = 0.05668
## alternative hypothesis: true location shift is not equal to 0
pr_test_result <- wilcox.test(best_est ~ pr, data = state_actor, exact = FALSE)
print(pr_test_result)
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  best_est by pr
## W = 325454, p-value = 1.895e-07
## alternative hypothesis: true location shift is not equal to 0
mis_stats_act <- state_actor %>%
  summarise(
    Mean = mean(misalign, na.rm = TRUE),
    Median = median(misalign, na.rm = TRUE),
    Mode = get_mode(misalign),
    Standard_Deviation = sd(misalign, na.rm = TRUE)
  )
print(mis_stats_act)
##        Mean Median Mode Standard_Deviation
## 1 0.3928209      0    0          0.4884603
scaled_stats_act <- state_actor %>%
  summarise(
    Mean = mean(scaled, na.rm = TRUE),
    Median = median(scaled, na.rm = TRUE),
    Mode = get_mode(scaled),
    Standard_Deviation = sd(scaled, na.rm = TRUE)
  )
print(scaled_stats_act)
##       Mean Median Mode Standard_Deviation
## 1 2.870301      4    4           1.321508
pr_stats_act <- state_actor %>%
  summarise(
    Mean = mean(pr, na.rm = TRUE),
    Median = median(pr, na.rm = TRUE),
    Mode = get_mode(pr),
    Standard_Deviation = sd(pr, na.rm = TRUE)
  )
print(pr_stats_act)
##        Mean Median Mode Standard_Deviation
## 1 0.1005757      0    0           0.300817
## sum states of misaligned and fatalities
misal_stats_only <-state_actor %>%
  group_by(misalign) %>%
  summarise(
    Mean_Death = mean(best_est, na.rm = TRUE),  # Calculate mean, remove NA values if any
    SD_Death = sd(best_est, na.rm = TRUE)       # Calculate standard deviation
  )
print(misal_stats_only)
## # A tibble: 2 × 3
##   misalign Mean_Death SD_Death
##      <dbl>      <dbl>    <dbl>
## 1        0       5.59    72.3 
## 2        1       2.59     2.81
summary_afspa_act <-state_actor %>%
  group_by(afspa) %>%
  summarise(
    Mean_Death = mean(best_est, na.rm = TRUE),  # Calculate mean, remove NA values if any
    SD_Death = sd(best_est, na.rm = TRUE)       # Calculate standard deviation
  )
print(summary_afspa_act)
## # A tibble: 2 × 3
##   afspa Mean_Death SD_Death
##   <int>      <dbl>    <dbl>
## 1     0       2.82     3.38
## 2     1       5.20    69.0
summary_state_act <-state_actor %>%
  group_by(State, misalign) %>%
  summarise(
    Mean_Death = mean(best_est, na.rm = TRUE),  # Calculate mean, remove NA values if any
    SD_Death = sd(best_est, na.rm = TRUE)       # Calculate standard deviation
  )
## `summarise()` has grouped output by 'State'. You can override using the
## `.groups` argument.
view(summary_state_act)
####
filtered_state_actor <- state_actor %>%
  filter(best_est <= quantile(best_est, 0.95))  # Remove high outliers, keeping up to the 95th percentile

ggplot(filtered_state_actor, aes(x = factor(misalign), y = best_est, fill = factor(misalign))) +
  geom_boxplot(outlier.shape = NA) +  # Boxplot to show medians and distributions
  labs(title = "Fatality Rates by Alignment",
       x = "Alignment",
       y = "Fatality Rates") +
  theme_minimal() +
  geom_jitter(width = 0.2, alpha = 0.5, color = "black")

table(state_only$type_of_violence)
## 
##  3 
## 21
table(state_only$align)
## < table of extent 0 >
table(state_only$scaled)
## 
## 1 2 4 
## 6 6 9
table(state_only$central_party)
## 
## INC NDA  NF UPA 
##   1   9   2   9
table(state_only$state_party)
## 
##   AITC    BJP CPI(M)    INC    JMM    NPF    SAD    TDP VACANT  YSRCP 
##      2      2      4      7      1      1      1      1      1      1
table(state_only$side_a)
## 
## Government of India 
##                  21
table(state_only$side_b)
## 
## Civilians 
##        21
table(state_only$State)
## 
## Andhra Pradesh          Assam          Bihar      Jharkhand        Manipur 
##              2              3              1              2              1 
##      Meghalaya       Nagaland         Punjab        Tripura    West Bengal 
##              1              2              1              4              4
table(state_only$pr)
## 
##  0  1 
## 20  1
contingency_table_actor <- state_actor%>%
  count(pr, misalign) %>%
  group_by(misalign) %>%
  mutate(proportion = n / sum(n)) %>%
  ungroup()

# Display the table
print(contingency_table_actor)
## # A tibble: 4 × 4
##      pr misalign     n proportion
##   <dbl>    <dbl> <int>      <dbl>
## 1     0        0  1533     0.855 
## 2     0        1  1123     0.968 
## 3     1        0   260     0.145 
## 4     1        1    37     0.0319
ggplot(contingency_table_actor, aes(x = factor(misalign), y = proportion, fill = factor(pr))) +
  geom_bar(stat = "identity", position = position_dodge()) +
  labs(title = "Proportion of PR by Alignment",
       x = "misalignment",
       y = "Proportion",
       fill = "PR") +
  geom_text(aes(label = scales::percent(proportion), y = proportion + 0.02),
            position = position_dodge(width = 0.9),
            vjust = 0,
            color = "black") +
  theme_minimal()

#kruskal wallis test
kruskal.test(best_est ~ misalign, data = state_actor)
## 
##  Kruskal-Wallis rank sum test
## 
## data:  best_est by misalign
## Kruskal-Wallis chi-squared = 7.7531, df = 1, p-value = 0.005362
library(dunn.test)
dunn_result <- dunn.test(state_actor$best_est, state_actor$misalign, method = "bonferroni")
##   Kruskal-Wallis rank sum test
## 
## data: x and group
## Kruskal-Wallis chi-squared = 7.7531, df = 1, p-value = 0.01
## 
## 
##                            Comparison of x by group                            
##                                  (Bonferroni)                                  
## Col Mean-|
## Row Mean |          0
## ---------+-----------
##        1 |  -2.784430
##          |    0.0027*
## 
## alpha = 0.05
## Reject Ho if p <= alpha/2
print(dunn_result)
## $chi2
## [1] 7.753052
## 
## $Z
## [1] -2.78443
## 
## $P
## [1] 0.002681093
## 
## $P.adjusted
## [1] 0.002681093
## 
## $comparisons
## [1] "0 - 1"
Q1 <- quantile(state_actor$best_est, 0.25)
Q3 <- quantile(state_actor$best_est, 0.75)
IQR <- IQR(state_actor$best_est)

ggplot(state_actor, aes(x = factor(misalign), y = best_est, fill = factor(misalign))) +
  geom_boxplot() +
  coord_cartesian(ylim = c(Q1 - 1.5 * IQR, Q3 + 1.5 * IQR)) + # Adjust axis limits to IQR range
  labs(title = "Comparison of Best Estimates by Misalignment Group",
       x = "Misalignment Group",
       y = "Best Estimates") +
  theme_minimal()

ggplot(state_actor, aes(x = factor(pr), y = best_est, fill = factor(pr))) +
  geom_boxplot() +
  coord_cartesian(ylim = c(Q1 - 1.5 * IQR, Q3 + 1.5 * IQR)) + # Adjust axis limits to IQR range
  labs(title = "Comparison of Best Estimates by PR",
       x = "PR",
       y = "Best Estimates") +
  theme_minimal()

ggplot(state_actor, aes(x = factor(afspa), y = best_est, fill = factor(afspa))) +
  geom_boxplot() +
  coord_cartesian(ylim = c(Q1 - 1.5 * IQR, Q3 + 1.5 * IQR)) + # Adjust axis limits to IQR range
  labs(title = "Comparison of Best Estimates by AFSPA",
       x = "AFSPA",
       y = "Best Estimates") +
  theme_minimal()

# Assuming state_actor is your dataframe, and it has the columns year, misalign, and best_est
sum_year <- state_actor %>%
  group_by(Year, misalign) %>%
  summarise(
    median_best_est = median(best_est, na.rm = TRUE),
    lower_quartile = quantile(best_est, 0.25, na.rm = TRUE),
    upper_quartile = quantile(best_est, 0.75, na.rm = TRUE)
  ) %>%
  ungroup()
## `summarise()` has grouped output by 'Year'. You can override using the
## `.groups` argument.
ggplot(sum_year, aes(x = factor(misalign), y = median_best_est, fill = factor(Year))) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_errorbar(aes(ymin = lower_quartile, ymax = upper_quartile), width = 0.2, position = position_dodge(0.9)) +
  labs(title = "Median Fatality Rates by Misalignment and Year",
       x = "Misalignment",
       y = "Median Fatality Rates",
       fill = "Year") +
  theme_minimal()

sum_state <- state_actor %>%
  group_by(State, misalign) %>%
  summarise(
    median_best_est = median(best_est, na.rm = TRUE),
    lower_quartile = quantile(best_est, 0.25, na.rm = TRUE),
    upper_quartile = quantile(best_est, 0.75, na.rm = TRUE)
  ) %>%
  ungroup()
## `summarise()` has grouped output by 'State'. You can override using the
## `.groups` argument.
ggplot(sum_state, aes(x = factor(misalign), y = median_best_est, fill = factor(State))) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_errorbar(aes(ymin = lower_quartile, ymax = upper_quartile), width = 0.2, position = position_dodge(0.9)) +
  labs(title = "Median Fatality Rates by Misalignment and State",
       x = "Misalignment",
       y = "Median Fatality Rates",
       fill = "State") +
  theme_minimal()

ggplot(sum_year, aes(x = Year, y = median_best_est, group = misalign, color = factor(misalign))) +
  geom_line() +
  labs(title = "Median Fatality Rates by Year and Misalignment",
       x = "Year",
       y = "Median Fatality Rates",
       color = "Misalignment") +
  theme_minimal()

bjp<- state_actor%>%
  filter(central_party%in% c('BJP','NDA'))
summary(bjp)
##       id               relid               Year           active_year       
##  Length:1032        Length:1032        Length:1032        Length:1032       
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##  code_status        type_of_violence   conflict_dset_id   conflict_new_id   
##  Length:1032        Length:1032        Length:1032        Length:1032       
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##  conflict_name      dyad_dset_id       dyad_new_id         dyad_name        
##  Length:1032        Length:1032        Length:1032        Length:1032       
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##  side_a_dset_id     side_a_new_id         side_a          side_b_dset_id    
##  Length:1032        Length:1032        Length:1032        Length:1032       
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##  side_b_new_id         side_b          number_of_sources source_article    
##  Length:1032        Length:1032        Min.   :-1.0000   Length:1032       
##  Class :character   Class :character   1st Qu.:-1.0000   Class :character  
##  Mode  :character   Mode  :character   Median :-1.0000   Mode  :character  
##                                        Mean   : 0.1541                     
##                                        3rd Qu.: 1.0000                     
##                                        Max.   : 7.0000                     
##                                                                            
##  source_office      source_date        source_headline    source_original   
##  Length:1032        Length:1032        Length:1032        Length:1032       
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##    where_prec    where_coordinates  where_description     State          
##  Min.   :1.000   Length:1032        Length:1032        Length:1032       
##  1st Qu.:2.000   Class :character   Class :character   Class :character  
##  Median :3.000   Mode  :character   Mode  :character   Mode  :character  
##  Mean   :2.461                                                           
##  3rd Qu.:3.000                                                           
##  Max.   :5.000                                                           
##                                                                          
##     adm_2             latitude          longitude           geom_wkt        
##  Length:1032        Length:1032        Length:1032        Length:1032       
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##  priogrid_gid         country           country_id           region         
##  Length:1032        Length:1032        Length:1032        Length:1032       
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##                                                                             
##                                                                             
##                                                                             
##                                                                             
##  event_clarity        date_prec     date_start          date_end        
##  Length:1032        Min.   :1.00   Length:1032        Length:1032       
##  Class :character   1st Qu.:1.00   Class :character   Class :character  
##  Mode  :character   Median :1.00   Mode  :character   Mode  :character  
##                     Mean   :1.09                                        
##                     3rd Qu.:1.00                                        
##                     Max.   :5.00                                        
##                                                                         
##     deaths_a          deaths_b     deaths_civilians  deaths_unknown    
##  Min.   : 0.0000   Min.   : 0.00   Min.   : 0.0000   Min.   : 0.00000  
##  1st Qu.: 0.0000   1st Qu.: 0.00   1st Qu.: 0.0000   1st Qu.: 0.00000  
##  Median : 0.0000   Median : 1.00   Median : 0.0000   Median : 0.00000  
##  Mean   : 0.9331   Mean   : 1.39   Mean   : 0.1764   Mean   : 0.06977  
##  3rd Qu.: 1.0000   3rd Qu.: 2.00   3rd Qu.: 0.0000   3rd Qu.: 0.00000  
##  Max.   :26.0000   Max.   :14.00   Max.   :14.0000   Max.   :18.00000  
##                                                                        
##     best_est         high_est         low_est       civilian_fatalities
##  Min.   : 0.000   Min.   : 1.000   Min.   : 0.000   Min.   :   0.0     
##  1st Qu.: 1.000   1st Qu.: 1.000   1st Qu.: 1.000   1st Qu.:  15.0     
##  Median : 2.000   Median : 2.000   Median : 2.000   Median :  35.0     
##  Mean   : 2.569   Mean   : 2.763   Mean   : 2.512   Mean   : 213.4     
##  3rd Qu.: 3.000   3rd Qu.: 3.000   3rd Qu.: 3.000   3rd Qu.: 224.0     
##  Max.   :26.000   Max.   :26.000   Max.   :26.000   Max.   :1024.0     
##                                                                        
##  sf_fatalities   insurgent_fatalities     afspa             pr         
##  Min.   :  0.0   Min.   :   0.0       Min.   :0.000   Min.   :0.00000  
##  1st Qu.:  8.0   1st Qu.:  23.0       1st Qu.:0.000   1st Qu.:0.00000  
##  Median : 25.0   Median :  68.0       Median :1.000   Median :0.00000  
##  Mean   :134.7   Mean   : 486.8       Mean   :0.626   Mean   :0.01163  
##  3rd Qu.:248.0   3rd Qu.: 262.0       3rd Qu.:1.000   3rd Qu.:0.00000  
##  Max.   :628.0   Max.   :2345.0       Max.   :1.000   Max.   :1.00000  
##                                                                        
##     duration       reasons          state_party        central_party     
##  Min.   : 26.0   Length:1032        Length:1032        Length:1032       
##  1st Qu.: 81.5   Class :character   Class :character   Class :character  
##  Median :156.0   Mode  :character   Mode  :character   Mode  :character  
##  Mean   :137.5                                                           
##  3rd Qu.:212.0                                                           
##  Max.   :212.0                                                           
##  NA's   :1020                                                            
##   misalignment        scaled        X_merge             state          
##  Min.   :0.0000   Min.   :1.000   Length:1032        Length:1032       
##  1st Qu.:1.0000   1st Qu.:1.000   Class :character   Class :character  
##  Median :1.0000   Median :1.000   Mode  :character   Mode  :character  
##  Mean   :0.8091   Mean   :1.755                                        
##  3rd Qu.:1.0000   3rd Qu.:2.000                                        
##  Max.   :1.0000   Max.   :4.000                                        
##                                                                        
##     misalign    
##  Min.   :0.000  
##  1st Qu.:1.000  
##  Median :1.000  
##  Mean   :0.813  
##  3rd Qu.:1.000  
##  Max.   :1.000  
## 
table(bjp$misalign)
## 
##   0   1 
## 193 839
table(bjp$pr)
## 
##    0    1 
## 1020   12
table(bjp$afspa)
## 
##   0   1 
## 386 646
table(bjp$state_party)
## 
##    AGP   AITC    BJD    BJP CPI(M)    INC    IND    JDU    JMM   MSCP   NDPP 
##    108      1     69    113     88    354      3     40     44     30      7 
##    NPF    NPP    RJD    SAD     SP    TDP    UDP VACANT  YSRCP 
##     13      1     32      5      6    105      1      6      6
bjp_reg<- lm(best_est ~ misalign + State, data = bjp)
summary(bjp_reg)
## 
## Call:
## lm(formula = best_est ~ misalign + State, data = bjp)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -3.4941 -1.4679 -0.6959  0.5671 22.7985 
## 
## Coefficients:
##                        Estimate Std. Error t value Pr(>|t|)    
## (Intercept)              2.4679     0.3553   6.946  6.7e-12 ***
## misalign                 0.2280     0.2799   0.815  0.41546    
## StateArunachal Pradesh  -1.3700     0.6952  -1.971  0.04903 *  
## StateAssam              -0.4943     0.2838  -1.742  0.08187 .  
## StateBihar               0.5974     0.4256   1.404  0.16068    
## StateJharkhand           0.7337     0.3865   1.898  0.05794 .  
## StateManipur             0.7982     0.3782   2.111  0.03506 *  
## StateMeghalaya          -1.2619     0.4878  -2.587  0.00982 ** 
## StateNagaland            0.3296     0.6708   0.491  0.62330    
## StateOdisha             -0.7829     0.4116  -1.902  0.05744 .  
## StatePunjab              0.5321     1.2667   0.420  0.67452    
## StateTripura             0.4013     0.3833   1.047  0.29540    
## StateWest Bengal        -0.1959     1.3821  -0.142  0.88731    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.719 on 1019 degrees of freedom
## Multiple R-squared:  0.04641,    Adjusted R-squared:  0.03518 
## F-statistic: 4.133 on 12 and 1019 DF,  p-value: 2.395e-06
sum_bjp <- bjp %>%
  group_by(State, misalign) %>%
  summarise(
    median_best_est = median(best_est, na.rm = TRUE),
    lower_quartile = quantile(best_est, 0.25, na.rm = TRUE),
    upper_quartile = quantile(best_est, 0.75, na.rm = TRUE)
  ) %>%
  ungroup()
## `summarise()` has grouped output by 'State'. You can override using the
## `.groups` argument.
ggplot(sum_bjp, aes(x = factor(misalign), y = median_best_est, fill = factor(State))) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_errorbar(aes(ymin = lower_quartile, ymax = upper_quartile), width = 0.2, position = position_dodge(0.9)) +
  labs(title = "Median Fatality Rates by Misalignment and State",
       x = "Misalignment",
       y = "Median Fatality Rates",
       fill = "State") +
  theme_minimal()

bjp_year <- bjp %>%
  group_by(Year, misalign) %>%
  summarise(
    median_best_est = median(best_est, na.rm = TRUE),
    lower_quartile = quantile(best_est, 0.25, na.rm = TRUE),
    upper_quartile = quantile(best_est, 0.75, na.rm = TRUE)
  ) %>%
  ungroup()
## `summarise()` has grouped output by 'Year'. You can override using the
## `.groups` argument.
ggplot(bjp_year, aes(x = factor(misalign), y = median_best_est, fill = factor(Year))) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_errorbar(aes(ymin = lower_quartile, ymax = upper_quartile), width = 0.2, position = position_dodge(0.9)) +
  labs(title = "Median Fatality Rates by Misalignment and Year",
       x = "Misalignment",
       y = "Median Fatality Rates",
       fill = "Year") +
  theme_minimal()

ggplot(sum_year, aes(x = Year, y = median_best_est, group = misalign, color = factor(misalign))) +
  geom_line() +
  labs(title = "Median Fatality Rates by Year and Misalignment",
       x = "Year",
       y = "Median Fatality Rates",
       color = "Misalignment") +
  theme_minimal()

ggplot(bjp_year, aes(x = Year, y = median_best_est, group = misalign, color = factor(misalign))) +
  geom_line() +
  labs(title = "Median Fatality Rates by Year and Misalignment",
       x = "Year",
       y = "Median Fatality Rates",
       color = "Misalignment") +
  theme_minimal()