UNDP Internship Test_Niharika Pola

Published

February 2, 2024

# Loading necessary libraries
library(ggplot2)
library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ lubridate 1.9.2     ✔ tibble    3.2.1
✔ purrr     1.0.1     ✔ tidyr     1.3.0
✔ readr     2.1.4     
── 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(lubridate)
library(viridis)
Loading required package: viridisLite
library(rnaturalearth)
library(sf)
Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
library(rnaturalearthhires)
library(leaflet)
library(htmlwidgets)
library(readr)
library(syuzhet)
library(tidytext)
library(wordcloud)
Loading required package: RColorBrewer
library(RColorBrewer)
library(grid)
# Reading the datasets
political_violence <- read.csv("Internship_Test_Feb2024/Internship_Test_Feb2024/Nigeria ACLED Export.csv")
news_data <- read.csv("Internship_Test_Feb2024/Internship_Test_Feb2024/Nigeria News EMM Export.csv")
View(political_violence)
View(news_data)

1. Analyzing the violence profile of Nigeria between 2022-2023

Data exploration and cleaning:

# Structure of the political violence data
str(political_violence)
'data.frame':   1902 obs. of  33 variables:
 $ ACLED.Actor1           : chr  "Police Forces of Nigeria (2015-)" "Military Forces of Nigeria (2015-)" "Military Forces of Nigeria (2015-)" "Military Forces of Nigeria (2015-)" ...
 $ ACLED.Actor1..group.   : chr  "State Security Forces" "State Security Forces" "State Security Forces" "State Security Forces" ...
 $ ACLED.Actor2           : chr  "Police Forces of Nigeria (2015-)" "Military Forces of Nigeria (2015-)" "Police Forces of Nigeria (2015-)" "Police Forces of Nigeria (2015-)" ...
 $ ACLED.Admin1           : chr  "Abia" "Imo" "Lagos" "Ogun" ...
 $ ACLED.Admin2           : chr  "Umuahia North" "Oguta" "Amowo-Odofin" "Shagamu" ...
 $ ACLED.Admin3           : logi  NA NA NA NA NA NA ...
 $ ACLED.Ally.Actor1      : chr  "" "" "" "" ...
 $ ACLED.Ally.Actor2      : chr  "" "" "" "" ...
 $ ACLED.CreatedOn        : chr  "12/12/2022 3:33" "12/6/2022 15:53" "12/13/2022 9:05" "2/21/2023 9:05" ...
 $ ACLED.Event.ID.Cnty    : chr  "NIG28349" "NIG28909" "NIG29012" "NIG29996" ...
 $ ACLED.Event.ID.No.Cnty : int  28349 28909 29012 29996 28350 28708 28626 29212 29211 29151 ...
 $ ACLED.Event.SubType    : chr  "Armed clash" "Armed clash" "Armed clash" "Armed clash" ...
 $ ACLED.Event.SubTypeDesc: chr  "Armed, organized groups engage in a battle, and no reports indicate a change in territorial control." "Armed, organized groups engage in a battle, and no reports indicate a change in territorial control." "Armed, organized groups engage in a battle, and no reports indicate a change in territorial control." "Armed, organized groups engage in a battle, and no reports indicate a change in territorial control." ...
 $ ACLED.Event.Type       : chr  "Battles" "Battles" "Battles" "Battles" ...
 $ ACLED.Event.TypeDesc   : chr  "A violent interaction between two politically organized armed groups at a particular time and location." "A violent interaction between two politically organized armed groups at a particular time and location." "A violent interaction between two politically organized armed groups at a particular time and location." "A violent interaction between two politically organized armed groups at a particular time and location." ...
 $ ACLED.Location         : chr  "Umuahia" "Izombe" "Satellite Town" "Ogigo" ...
 $ ACLED.Notes            : chr  "On 15 October 2022, a policeman shot and killed his colleague in Umuahia (Umuahia North, Abia) following an arg"| __truncated__ "On 28 November 2022, suspected security operatives dressed in military uniforms shot the security officers (pre"| __truncated__ "On 3 December 2022, some naval officers clashed with policemen in Satellite town (Amowo-Odofin, Lagos) followin"| __truncated__ "On 15 February 2023, soldiers from 174 battalion wounded an unspecified number of policemen and other persons w"| __truncated__ ...
 $ ACLED.Region           : chr  "Western Africa" "Western Africa" "Western Africa" "Western Africa" ...
 $ ACLED.Source           : chr  "Premium Times (Nigeria)" "Daily Trust (Nigeria)" "Daily Trust (Nigeria); Nigeria Punch" "Daily Trust (Nigeria); Nigeria Punch" ...
 $ ACLED.SourceScale      : chr  "National" "National" "National" "National" ...
 $ ACLED.Year             : int  2022 2022 2022 2023 2022 2022 2022 2022 2022 2022 ...
 $ Geographic.Area        : chr  "South" "South" "South" "South" ...
 $ ACLED.Fatalities       : int  1 0 1 0 1 3 0 0 0 1 ...
 $ ACLED.Geo.Precision    : int  1 1 1 1 1 1 1 1 1 1 ...
 $ ACLED.Geometrry        : chr  "Point" "Point" "Point" "Point" ...
 $ Acled.Gwno             : int  NA NA NA NA NA NA NA NA NA NA ...
 $ ACLED.Inter1           : int  1 1 1 1 1 1 1 1 1 1 ...
 $ ACLED.Inter2           : int  1 1 1 1 1 1 1 2 2 2 ...
 $ ACLED.Interaction      : int  11 11 11 11 11 11 11 12 12 12 ...
 $ ACLED.Latitude         : num  5.53 5.63 6.44 6.7 12.45 ...
 $ ACLED.Longitude        : num  7.49 6.87 3.25 3.51 4.2 ...
 $ Acled.Pk               : int  4083963 4068208 4091266 4169404 4080329 4060350 4053964 4098416 4098415 4096637 ...
 $ TimeFK.Event.Date      : int  20221015 20221128 20221203 20230215 20221001 20221117 20221109 20221214 20221214 20221208 ...
colSums(is.na(political_violence))
           ACLED.Actor1    ACLED.Actor1..group.            ACLED.Actor2 
                      0                       0                       0 
           ACLED.Admin1            ACLED.Admin2            ACLED.Admin3 
                      0                       0                    1902 
      ACLED.Ally.Actor1       ACLED.Ally.Actor2         ACLED.CreatedOn 
                      0                       0                       0 
    ACLED.Event.ID.Cnty  ACLED.Event.ID.No.Cnty     ACLED.Event.SubType 
                      0                       0                       0 
ACLED.Event.SubTypeDesc        ACLED.Event.Type    ACLED.Event.TypeDesc 
                      0                       0                       0 
         ACLED.Location             ACLED.Notes            ACLED.Region 
                      0                       0                       0 
           ACLED.Source       ACLED.SourceScale              ACLED.Year 
                      0                       0                       0 
        Geographic.Area        ACLED.Fatalities     ACLED.Geo.Precision 
                      0                       0                       0 
        ACLED.Geometrry              Acled.Gwno            ACLED.Inter1 
                      0                    1772                       0 
           ACLED.Inter2       ACLED.Interaction          ACLED.Latitude 
                      0                       0                       0 
        ACLED.Longitude                Acled.Pk       TimeFK.Event.Date 
                      0                       0                       0 
# Dropping columns with no data
political_violence <- political_violence %>%
  select(-c(ACLED.Admin3, Acled.Gwno))

# Standardizing text columns to lower case and remove leading/trailing spaces
political_violence <- political_violence %>%
  mutate_at(vars(ACLED.Event.Type, ACLED.Actor1, ACLED.Actor2, ACLED.Admin1, ACLED.Admin2), list(~trimws(tolower(.))))

# Filling missing Actor2 values
political_violence$ACLED.Actor2 <- ifelse(is.na(political_violence$ACLED.Actor2), 
                                          "Not Applicable", 
                                          political_violence$ACLED.Actor2)

# Removing duplicates
political_violence <- political_violence %>%
  distinct()

# Converting Date Columns
political_violence$ACLED.CreatedOn <- as.Date(political_violence$ACLED.CreatedOn, format="%m/%d/%Y %H:%M")

# Renaming Columns for Convenience
names(political_violence) <- gsub("ACLED.", "", names(political_violence))
names(political_violence) <- gsub("\\.$", "", names(political_violence)) 
names(political_violence) <- gsub("\\.\\.", "_", names(political_violence)) 
names(political_violence) <- gsub("\\.", "_", names(political_violence)) 
 
colnames(political_violence)
 [1] "Actor1"            "Actor1_group"      "Actor2"           
 [4] "Admin1"            "Admin2"            "Ally_Actor1"      
 [7] "Ally_Actor2"       "CreatedOn"         "Event_ID_Cnty"    
[10] "Event_ID_No_Cnty"  "Event_SubType"     "Event_SubTypeDesc"
[13] "Event_Type"        "Event_TypeDesc"    "Location"         
[16] "Notes"             "Region"            "Source"           
[19] "SourceScale"       "Year"              "Geographic_Area"  
[22] "Fatalities"        "Geo_Precision"     "Geometrry"        
[25] "Inter1"            "Inter2"            "Interaction"      
[28] "Latitude"          "Longitude"         "Acled_Pk"         
[31] "TimeFK_Event_Date"
# Summary of numerical variables
summary(political_violence[,sapply(political_violence, is.numeric)])
 Event_ID_No_Cnty      Year        Fatalities      Geo_Precision  
 Min.   :26494    Min.   :2022   Min.   :  0.000   Min.   :1.000  
 1st Qu.:28674    1st Qu.:2022   1st Qu.:  0.000   1st Qu.:1.000  
 Median :29158    Median :2022   Median :  0.000   Median :1.000  
 Mean   :29051    Mean   :2022   Mean   :  1.977   Mean   :1.398  
 3rd Qu.:29639    3rd Qu.:2023   3rd Qu.:  1.000   3rd Qu.:2.000  
 Max.   :30117    Max.   :2023   Max.   :150.000   Max.   :3.000  
     Inter1          Inter2       Interaction       Latitude     
 Min.   :1.000   Min.   :0.000   Min.   :10.00   Min.   : 4.511  
 1st Qu.:3.000   1st Qu.:1.000   1st Qu.:16.00   1st Qu.: 6.451  
 Median :3.000   Median :5.000   Median :37.00   Median : 8.876  
 Mean   :3.416   Mean   :4.326   Mean   :35.82   Mean   : 8.928  
 3rd Qu.:4.000   3rd Qu.:7.000   3rd Qu.:47.00   3rd Qu.:11.487  
 Max.   :8.000   Max.   :8.000   Max.   :70.00   Max.   :13.729  
   Longitude         Acled_Pk       TimeFK_Event_Date 
 Min.   : 2.850   Min.   :4033565   Min.   :20221001  
 1st Qu.: 6.208   1st Qu.:4067888   1st Qu.:20221107  
 Median : 7.196   Median :4097680   Median :20221212  
 Mean   : 7.578   Mean   :4102586   Mean   :20224341  
 3rd Qu.: 8.209   3rd Qu.:4139442   3rd Qu.:20230116  
 Max.   :14.251   Max.   :4178742   Max.   :20230224  
# Distribution of Event Types
table(political_violence$Event_Type)

                   battles explosions/remote violence 
                       474                         96 
                  protests                      riots 
                       255                        180 
    strategic developments violence against civilians 
                       129                        768 
# Distribution of Actors
table(political_violence$Actor1_group)

             Amasiri Communal Militia (Nigeria) 
                                              3 
 Anambra State Signage and Advertisement Agency 
                                              1 
                                  Armed Bandits 
                                            430 
                            Civilians (Nigeria) 
                                              1 
                              Communal militias 
                                            540 
                   Eiye Confraternity (Nigeria) 
                                              3 
                  Government of Nigeria (2015-) 
                                              2 
                          Islamic State (Sahel) 
                                              1 
                                  Jihadi Groups 
                                            128 
                               Kalare Boys Gang 
                                              1 
          Kashimbila Communal Militia (Nigeria) 
                                              1 
              Koseru Communal Militia (Nigeria) 
                                              1 
              Kwayam Communal Militia (Nigeria) 
                                              1 
             Lambata Communal Militia (Nigeria) 
                                              1 
             Monguno Communal Militia (Nigeria) 
                                              1 
               Okomu Communal Militia (Nigeria) 
                                              2 
                           Protesters (Nigeria) 
                                            255 
                              Rioters (Nigeria) 
                                            180 
         SDP: Social Democratic Party (Nigeria) 
                                              1 
                          State Security Forces 
                                            344 
             Ughoton Communal Militia (Nigeria) 
                                              1 
Zamfara State Anti-thuggery Committee (Nigeria) 
                                              3 
              Zandam Communal Militia (Nigeria) 
                                              1 

Summary Interpretation:

  1. Numerical Variables Summary:

    • Event ID, Year, Fatalities, Geo Precision, Inter1, Inter2, Interaction, Latitude, Longitude, Acled.Pk, TimeFK.Event.Date: These provide a quantitative overview of the events, including the range of fatalities, geographic precision of event locations, interaction types, and temporal spread. The data primarily spans the years 2022 to 2023, with fatalities per event ranging from 0 to 150, indicating a wide variance in the severity of events.
  2. Fatalities:

    • The majority of events have no fatalities, but there are outliers with a significant number of fatalities, up to 150. This suggests a mix of non-lethal and highly lethal violent incidents.
  3. Geographic Precision:

    • Most events are precisely geolocated (Geo Precision mostly 1), which allows for detailed spatial analysis to identify hotspots of violence.
  4. Interaction Types:

    • The interaction types (Inter 1, Inter 2 and Interaction) span a wide range, suggesting a variety of conflict dynamics, possibly including state forces, non-state actors, and civilians.
  5. Geographic Distribution:

    • The latitude and longitude values indicate events are spread across Nigeria, with potential concentration in specific regions based on the median and quartile ranges.

Now let’s proceed to our first question.

1a. What are the most common Event Types of political violence?

To find the most common event types, I grouped the data by the event type and count the number of occurrences of each type.

# Count the number of occurrences of each event type
event_type_counts <- political_violence %>%
  group_by(Event_Type) %>%
  summarise(Count = n()) %>%
  arrange(desc(Count))

event_type_counts <- event_type_counts %>%
  mutate(Event_Type = factor(Event_Type),
         Count = as.numeric(Count))

# Sorting data to have a meaningful gradient effect based on Count
event_type_counts <- event_type_counts %>%
  arrange(desc(Count))

# Calculate a gradient based on Count
event_type_counts$Gradient = rank(-event_type_counts$Count)

# Capitalize the first letter of each event type
event_type_counts$Event_Type <- str_to_title(event_type_counts$Event_Type)

# plot 
ggplot(event_type_counts, aes(x=reorder(Event_Type, Count), y=Count, fill=Count)) +
  geom_bar(stat="identity") +
  scale_fill_gradient(low = "lightblue", high = "darkblue") +
  geom_text(aes(label=Count, size=14), hjust=1.1, vjust=0.5, color="white", face="bold") +
  coord_flip() +
  labs(title = "Most Common Event Types of \nPolitical Violence In Nigeria",
       x = "Event Type",
       y = "Number Of Events") +
  theme_minimal() +
  theme(legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 15, face = "bold", margin = margin(b = 13)),
        axis.title.x = element_text(size = 14, face = "bold"),
        axis.title.y = element_text(size = 14, face = "bold"),
        axis.text.x = element_text(size = 13, face = "bold"),
        axis.text.y = element_text(size = 13, face = "bold", color = "black"),
        plot.margin = margin(1, 1, 1, 1, "cm"))

# Save the plot with a specified width and height
ggsave("event_types_plot.png", width = 15, height = 8, units = "in")

1b. Which actors are the highest risk actors? (Fatality vs Number of Events)

To determine which actors are the highest risk in terms of political violence in Nigeria, I analyzed the data to identify the actors associated with the highest number of events and fatalities. This involved aggregating the data by actors (Actor1 and Actor2), then calculating the total fatalities and number of events for each actor.

# Preparing the data: Aggregating by Actor1_group
actor_risk_profile1 <- political_violence %>%
  group_by(Actor1_group) %>%
  summarise(Total_Fatalities = sum(Fatalities, na.rm = TRUE),
            Number_of_Events = n()) %>%
  filter(Number_of_Events > 10) %>%
  arrange(desc(Total_Fatalities))

# Visualizing actors with the highest fatalities 
ggplot(actor_risk_profile1, aes(x=reorder(Actor1_group, Total_Fatalities), y=Total_Fatalities, fill=Total_Fatalities)) +
  geom_bar(stat="identity") +
  scale_fill_gradient(low = "lightblue", high = "darkblue") +
  geom_text(aes(label=Total_Fatalities),  hjust=1.1, vjust=0.5, color="white") +
  coord_flip() +
  labs(title = "Actor1 Groups Associated with the Highest Fatalities",
       x = "Actor",
       y = "Total Fatalities") +
  theme_minimal() +
  theme(legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 10)),
        axis.title.x = element_text(size = 11, face = "bold"), 
        axis.title.y = element_text(size = 11, face = "bold"), 
        axis.text.x = element_text(size = 10, face = "bold"), 
        axis.text.y = element_text(size = 10, face = "bold", color = "black"), 
        plot.margin = margin(1, 1, 1, 1, "cm"))

# Visualizing actors by the number of events
ggplot(actor_risk_profile1, aes(x=reorder(Actor1_group, Number_of_Events), y=Number_of_Events, fill=Number_of_Events)) +
  geom_bar(stat="identity") +
  scale_fill_gradient(low = "orange", high = "red") +
  geom_text(aes(label=Number_of_Events),  hjust=1.1, vjust=0.5, color="white") +
  coord_flip() +
  labs(title = "Actor1 Groups Associated with the Highest Number of Events",
       x = "Actor",
       y = "Number of Events") +
  theme_minimal() +
  theme(legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 10)),
        axis.title.x = element_text(size = 11, face = "bold"), 
        axis.title.y = element_text(size = 11, face = "bold"), 
        axis.text.x = element_text(size = 10, face = "bold"), 
        axis.text.y = element_text(size = 10, face = "bold", color = "black"), 
        plot.margin = margin(1, 1, 1, 1, "cm"))

# Preparing the data: Aggregating by Actor1
actor_risk_profile2 <- political_violence %>%
  group_by(Actor1) %>%
  summarise(Total_Fatalities = sum(Fatalities, na.rm = TRUE),
            Number_of_Events = n()) %>%
  filter(Number_of_Events > 10) %>%
  arrange(desc(Total_Fatalities)) %>%
  top_n(10, Total_Fatalities) 

# Visualizing actors with the highest fatalities
ggplot(actor_risk_profile2, aes(x=reorder(Actor1, Total_Fatalities), y=Total_Fatalities, fill=Total_Fatalities)) +
  geom_bar(stat="identity") +
  scale_fill_gradient(low = "lightblue", high = "darkblue") +  # Adjust colors for gradient as needed
  geom_text(aes(label=Total_Fatalities), hjust=1, vjust=0.5, color="white", size=2) +
  coord_flip() +
  labs(title = "Top-10 Actors Associated with the \nHighest Fatalities (Actor-1)",
       x = "Actor",
       y = "Total Fatalities") +
  theme_minimal() +
  theme(legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 10, t = 20)),
        axis.title.x = element_text(size = 11, face = "bold"), 
        axis.title.y = element_text(size = 11, face = "bold"), 
        axis.text.x = element_text(size = 8, face = "bold"), 
        axis.text.y = element_text(size = 8, face = "bold", color = "black"),
        plot.margin = margin(1, 1, 1, 1, "cm"))

# Visualizing actors by the number of events
ggplot(actor_risk_profile2, aes(x=reorder(Actor1, Number_of_Events), y=Number_of_Events, fill=Number_of_Events)) +
  geom_bar(stat="identity") +
  scale_fill_gradient(low = "orange", high = "red") +  # Adjust colors for gradient as needed
  geom_text(aes(label=Number_of_Events), hjust=1, vjust=0.5, color="white", size=2) +
  coord_flip() +
  labs(title = "Top-10 Actors Associated with the \nHighest Number of Events \n(Actor1)",
       x = "Actor",
       y = "Number of Events") +
  theme_minimal() +
  theme(legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 10)),
        axis.title.x = element_text(size = 11, face = "bold"), 
        axis.title.y = element_text(size = 11, face = "bold"), 
        axis.text.x = element_text(size = 8, face = "bold"), 
        axis.text.y = element_text(size = 8, face = "bold", color = "black"),
        plot.margin = margin(1, 1, 1, 1, "cm"))

# Preparing the data: Aggregating by Actor2 
actor_risk_profile3 <- political_violence %>%
  group_by(Actor2) %>%
  summarise(Total_Fatalities = sum(Fatalities, na.rm = TRUE),
            Number_of_Events = n()) %>%
  filter(Number_of_Events > 10) %>%
  arrange(desc(Total_Fatalities)) %>%
  top_n(10, Total_Fatalities)


# Visualizing actors with the highest fatalities
ggplot(actor_risk_profile3, aes(x=reorder(Actor2, Total_Fatalities), y=Total_Fatalities, fill=Total_Fatalities)) +
  geom_bar(stat="identity") +
  scale_fill_gradient(low = "lightgreen", high = "darkgreen") +  # Gradient from light green to dark green
  geom_text(aes(label=Total_Fatalities), hjust=1, vjust=0.5, color="white", size=2) +
  coord_flip() +
  labs(title = "Top-10 Actors Associated with the \nHighest Fatalities (Actor-2)",
       x = "Actor",
       y = "Total Fatalities") +
  theme_minimal() +
  theme(legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 10, t = 20)),
        axis.title.x = element_text(size = 11, face = "bold"), 
        axis.title.y = element_text(size = 11, face = "bold"),
        axis.text.x = element_text(size = 8, face = "bold"), 
        axis.text.y = element_text(size = 8, face = "bold", color = "black"),
        plot.margin = margin(1, 1, 1, 1, "cm"))

# Visualizing actors by the number of events
ggplot(actor_risk_profile3, aes(x=reorder(Actor2, Number_of_Events), y=Number_of_Events, fill=Number_of_Events)) +
  geom_bar(stat="identity") +
  scale_fill_gradient(low = "lavender", high = "darkmagenta") +  # Gradient from light purple to dark purple
  geom_text(aes(label=Number_of_Events), hjust=1, vjust=0.5, color="white", size=2) +
  coord_flip() +
  labs(title = "Top-10 Actors Associated with the \nHighest Number of Events \n(Actor2)",
       x = "Actor",
       y = "Number of Events") +
  theme_minimal() +
  theme(legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 10)),
        axis.title.x = element_text(size = 11, face = "bold"), 
        axis.title.y = element_text(size = 11, face = "bold"), 
        axis.text.x = element_text(size = 8, face = "bold"), 
        axis.text.y = element_text(size = 8, face = "bold", color = "black"),
        plot.margin = margin(1, 1, 1, 1, "cm"))

# Generating Actor2 groups based Actor1 group categorization
categorize_actor <- function(actor_name) {
  if (is.na(actor_name)) {
    return(NA) # Return NA for missing values
  } else if (grepl("Military|Army|Forces", actor_name, ignore.case = TRUE)) {
    return("Military Forces")
  } else if (grepl("Rebels|Insurgents", actor_name, ignore.case = TRUE)) {
    return("Rebel Groups")
  } else if (grepl("Police", actor_name, ignore.case = TRUE)) {
    return("Police Forces")
  } else if (grepl("Civilians|Citizens", actor_name, ignore.case = TRUE)) {
    return("Civilians")
  } else {
    return("Other") # Use "Other" for actors that don't match any category
  }
}

# Apply the modified categorization function to Actor2
political_violence <- political_violence %>%
  mutate(Actor2_group = sapply(Actor2, categorize_actor))
# Preparing the data: Aggregating by Actor2 Group 
actor_risk_profile4 <- political_violence %>%
  group_by(Actor2_group) %>%
  summarise(Total_Fatalities = sum(Fatalities, na.rm = TRUE),
            Number_of_Events = n()) %>%
  filter(Number_of_Events > 10) %>%
  arrange(desc(Total_Fatalities))

# Visualizing actors with the highest fatalities 
ggplot(actor_risk_profile4, aes(x=reorder(Actor2_group, Total_Fatalities), y=Total_Fatalities, fill=Total_Fatalities)) +
  geom_bar(stat="identity") +
  scale_fill_gradient(low = "lightgreen", high = "darkgreen") +  # Gradient from light green to dark green
  geom_text(aes(label=Total_Fatalities), hjust=1.1, vjust=0.5, color="white") +
  coord_flip() +
  labs(title = "Actor2 Groups Associated with the Highest Fatalities",
       x = "Actor",
       y = "Total Fatalities") +
  theme_minimal() +
  theme(legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 10)),
        axis.title.x = element_text(size = 11, face = "bold"), 
        axis.title.y = element_text(size = 11, face = "bold"), 
        axis.text.x = element_text(size = 10, face = "bold"), 
        axis.text.y = element_text(size = 10, face = "bold", color = "black"), 
        plot.margin = margin(1, 1, 1, 1, "cm"))

# Visualizing actors by the number of events
ggplot(actor_risk_profile4, aes(x=reorder(Actor2_group, Number_of_Events), y=Number_of_Events, fill=Number_of_Events)) +
  geom_bar(stat="identity") +
  scale_fill_gradient(low = "lavender", high = "darkmagenta") +  # Gradient from lavender to dark magenta
  geom_text(aes(label=Number_of_Events), hjust=1.1, vjust=0.5, color="black") +
  coord_flip() +
  labs(title = "Actor2 Groups Associated with the Highest Number of Events",
       x = "Actor",
       y = "Number of Events") +
  theme_minimal() +
  theme(legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 10)),
        axis.title.x = element_text(size = 11, face = "bold"), 
        axis.title.y = element_text(size = 11, face = "bold"), 
        axis.text.x = element_text(size = 10, face = "bold"), 
        axis.text.y = element_text(size = 10, face = "bold", color = "black"), 
        plot.margin = margin(1, 1, 1, 1, "cm"))

1c. What is the geographic profile of the political violence?

Mapping or visualizing the geographic distribution of events can highlight areas with higher concentrations of violence.

# Load Nigeria's map with state boundaries
nigeria_map <- ne_states(country = "Nigeria", returnclass = "sf")

political_violence_sf <- st_as_sf(political_violence, coords = c("Longitude", "Latitude"), crs = 4326, agr = "constant")

# Spatial join - matches each event to a state based on location
events_by_state <- st_join(political_violence_sf, nigeria_map)

# Count events by state
event_counts <- events_by_state %>%
  group_by(name) %>%
  summarise(count = n(), .groups = 'drop')

event_counts <- as.data.frame(event_counts)

# Perform the join
nigeria_map_with_counts <- left_join(nigeria_map, event_counts, by = "name")


ggplot() +
  geom_sf(data = nigeria_map_with_counts, fill = "lightgray", color = "black") +
  geom_sf(data = political_violence_sf, color = "red", size = 2, alpha = 0.7) +
  geom_sf_text(data = nigeria_map_with_counts, aes(label = paste(name, count, sep=": ")), size = 3, check_overlap = TRUE, color = "blue") +
  labs(title = "Geographic Profile of Political Violence in Nigeria \nwith State Boundaries and Event Counts", x="Latitude", y="Longitude") + 
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 10)), 
        axis.title.x = element_text(size = 11, face = "bold"), 
        axis.title.y = element_text(size = 11, face = "bold"), 
        plot.margin = margin(1, 1, 1, 1, "cm"))

#interactive map
m <- leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>% 
  setView(lng = 8, lat = 10, zoom = 6) 


m <- m %>% addPolygons(data = nigeria_map_with_counts, fillColor = ~colorQuantile("YlOrRd", count)(count),
                       color = "#444444", weight = 1, opacity = 1,
                       fillOpacity = 0.7, smoothFactor = 0.5,
                       label = ~paste(name, ": ", count, " events"), 
                       highlightOptions = highlightOptions(weight = 2,
                                                           color = "#666",
                                                           fillOpacity = 0.7,
                                                           bringToFront = TRUE))


political_violence$popup_content <- paste("Event at:", political_violence$Latitude, ",", political_violence$Longitude)


political_violence_sf <- st_as_sf(political_violence, coords = c("Longitude", "Latitude"), crs = 4326, agr = "constant")

m <- m %>% addCircleMarkers(data = political_violence_sf, radius = 3, color = "#FF0000", stroke = FALSE, fillOpacity = 0.8,
                            popup = ~popup_content)



m <- m %>% addControl("<h4 style='margin:4px; padding:4px;'><b>Map Title: Interactive Map of Political Violence Events in Nigeria</b></h4>",
                      position = "topleft", className = "map-title")

# Display the map
m
saveWidget(m, 'NigeriaPoliticalViolenceMap.html', selfcontained = TRUE)

1b. What features of this data set have the most associative or predictive value?

library(corrplot)
corrplot 0.92 loaded
#perform correlation for numerical variables
correlation_matrix <- cor(political_violence[, sapply(political_violence, is.numeric)], use = "pairwise.complete.obs")

# Print the correlation matrix
print(correlation_matrix)
                  Event_ID_No_Cnty        Year   Fatalities Geo_Precision
Event_ID_No_Cnty       1.000000000  0.65797912 -0.002128291   -0.01015707
Year                   0.657979120  1.00000000 -0.018705052   -0.01518593
Fatalities            -0.002128291 -0.01870505  1.000000000    0.09954380
Geo_Precision         -0.010157071 -0.01518593  0.099543799    1.00000000
Inter1                -0.044620749 -0.01293238 -0.211439757   -0.21877497
Inter2                -0.007918116 -0.04452586 -0.040552486    0.11451028
Interaction           -0.044867219 -0.04472494 -0.200564340   -0.15948046
Latitude              -0.058248992 -0.12147395  0.167933451    0.22323515
Longitude             -0.024430417 -0.05743966  0.170105594    0.12436456
Acled_Pk               0.837874420  0.85062240 -0.008041039   -0.01029839
TimeFK_Event_Date      0.667221448  0.99986304 -0.018235320   -0.01536375
                       Inter1       Inter2 Interaction    Latitude   Longitude
Event_ID_No_Cnty  -0.04462075 -0.007918116 -0.04486722 -0.05824899 -0.02443042
Year              -0.01293238 -0.044525861 -0.04472494 -0.12147395 -0.05743966
Fatalities        -0.21143976 -0.040552486 -0.20056434  0.16793345  0.17010559
Geo_Precision     -0.21877497  0.114510277 -0.15948046  0.22323515  0.12436456
Inter1             1.00000000 -0.238767337  0.82733898 -0.19949917 -0.35035514
Inter2            -0.23876734  1.000000000  0.12973189  0.08632399 -0.10660375
Interaction        0.82733898  0.129731893  1.00000000 -0.14808662 -0.33061198
Latitude          -0.19949917  0.086323985 -0.14808662  1.00000000  0.38284950
Longitude         -0.35035514 -0.106603749 -0.33061198  0.38284950  1.00000000
Acled_Pk          -0.02726637 -0.038266174 -0.05494375 -0.10419859 -0.04089638
TimeFK_Event_Date -0.01341853 -0.044872052 -0.04512724 -0.12256638 -0.05771800
                      Acled_Pk TimeFK_Event_Date
Event_ID_No_Cnty   0.837874420        0.66722145
Year               0.850622404        0.99986304
Fatalities        -0.008041039       -0.01823532
Geo_Precision     -0.010298387       -0.01536375
Inter1            -0.027266371       -0.01341853
Inter2            -0.038266174       -0.04487205
Interaction       -0.054943747       -0.04512724
Latitude          -0.104198586       -0.12256638
Longitude         -0.040896384       -0.05771800
Acled_Pk           1.000000000        0.85630612
TimeFK_Event_Date  0.856306115        1.00000000
corrplot(correlation_matrix, method = "color", type = "upper", order = "hclust",
         tl.col = "black", tl.srt = 45, addCoef.col = "black", 
         cl.pos = 'b', cl.cex = 0.5, tl.cex = 0.5,
         # Adjust the size of correlation coefficients
         number.cex = 0.5)  # Reduce this value to make the text smaller

         # Title for the plot
         #main = "Correlation Matrix of Political Violence")

Strong Associations:

  • Acled_Pk and Year (0.85062240): This suggests a strong positive association, likely indicating that Acled_Pk increases with the year. It might represent a sequential identifier or timestamp that naturally increases over time.

  • TimeFK_Event_Date and Year (0.99986304): This very strong positive association is expected since TimeFK_Event_Date likely represents the event date that directly correlates with the year.

  • Acled_Pk and Event_ID_No_Cnty (0.837874420): Another strong positive association, suggesting these might both be identifiers or sequential numbers that increase together.

  • TimeFK_Event_Date and Acled_Pk (0.85630612): Indicates a strong positive association, reinforcing the idea that both variables are related to time or sequence.

Notable Associations:

  • Inter1 and Interaction (0.82733898): A strong positive association, indicating that these variables are related, possibly representing coded information where one variable directly influences or partakes in defining the other.

Geographic Associations:

  • Latitude and Longitude (0.38284950): This moderate positive association is logical, as events happening within the same geographic region would have somewhat correlated latitudes and longitudes.

Negative Associations:

  • Inter1 and Longitude (-0.35035514): Indicates a moderate negative association, suggesting that as one variable increases, the other tends to decrease. This might reflect geographic or regional specifics in the distribution of events.

Considerations:

  • Low or Insignificant Correlations: Variables like Fatalities show low correlations with most other variables, indicating that the number of fatalities in an event doesn’t strongly correlate linearly with the other numerical variables examined.
#performing chi-test for selected categorical variables 

library(vcd) # For the chisq.test function

library(vcd) # For the chisq.test function

cramers_v <- function(x, y) {
  tbl <- table(x, y)
  
  # Remove rows and columns that sum to zero
  tbl <- tbl[rowSums(tbl) > 0, colSums(tbl) > 0]
  
  if(nrow(tbl) < 2 | ncol(tbl) < 2) {
    return(0)  # Returns 0 if the table is too small to analyze
  }
  
  chi2 <- chisq.test(tbl, correct = FALSE)$statistic
  n <- sum(tbl)
  phi2 <- chi2 / n
  r <- nrow(tbl)
  k <- ncol(tbl)
  phi2corr <- max(0, phi2 - ((k-1)*(r-1))/(n-1))
  rcorr <- r - ((r-1)^2)/(n-1)
  kcorr <- k - ((k-1)^2)/(n-1)
  return(sqrt(phi2corr / min((kcorr-1), (rcorr-1))))
}

variables <- c('Actor1', 'Actor2', 'Event_Type', 'Admin1', 'Admin2', 'Event_SubType', 'Location', 'Year', 'Geographic_Area')
cramers_matrix <- matrix(NA, nrow = length(variables), ncol = length(variables), dimnames = list(variables, variables))

for (i in 1:length(variables)) {
  for (j in 1:length(variables)) {
    if (i != j) {
      cramers_matrix[i, j] <- cramers_v(political_violence[[variables[i]]], political_violence[[variables[j]]])
    } else {
      cramers_matrix[i, j] <- 0  # Set diagonal to 0
    }
  }
}

# View the association matrix
print(cramers_matrix)
                   Actor1    Actor2 Event_Type    Admin1    Admin2
Actor1          0.0000000 0.4483329 0.70094864 0.3884722 0.4087289
Actor2          0.4483329 0.0000000 0.57898438 0.2353246 0.2901929
Event_Type      0.7009486 0.5789844 0.00000000 0.2851925 0.3803758
Admin1          0.3884722 0.2353246 0.28519255 0.0000000 0.8839754
Admin2          0.4087289 0.2901929 0.38037583 0.8839754 0.0000000
Event_SubType   0.4089818 0.3088547 0.99630118 0.1665435 0.1843506
Location        0.3684197 0.2589330 0.31318174 0.7216047 0.8084308
Year            0.2141153 0.1237265 0.09077849 0.1723757 0.3032323
Geographic_Area 0.6348515 0.4718610 0.25586843 0.9912685 0.8773797
                Event_SubType  Location       Year Geographic_Area
Actor1              0.4089818 0.3684197 0.21411535       0.6348515
Actor2              0.3088547 0.2589330 0.12372654       0.4718610
Event_Type          0.9963012 0.3131817 0.09077849       0.2558684
Admin1              0.1665435 0.7216047 0.17237565       0.9912685
Admin2              0.1843506 0.8084308 0.30323234       0.8773797
Event_SubType       0.0000000 0.1037885 0.15105606       0.2943837
Location            0.1037885 0.0000000 0.26886091       0.7200567
Year                0.1510561 0.2688609 0.00000000       0.1417035
Geographic_Area     0.2943837 0.7200567 0.14170347       0.0000000

High Associations:

  • Event_Type and Event_SubType: Cramér’s V = 0.996, indicating a nearly perfect association. This suggests that the type of event is highly predictive of its subtype, which is expected given these variables likely have a hierarchical relationship.

  • Admin1 and Geographic_Area: Cramér’s V = 0.991, showing a very strong association. This indicates that the administrative level 1 location is almost perfectly indicative of the broader geographic area.

  • Admin2 and Admin1: Cramér’s V = 0.884, another strong association, suggesting that knowing the Admin2 location provides significant information about Admin1.

  • Admin2 and Geographic_Area: Cramér’s V = 0.877, also indicating a strong association between the specific location within Admin2 and the broader geographic area.

Moderate Associations:

  • Actor1 and Event_Type: Cramér’s V = 0.701, showing a moderate association, indicating that the actor involved in an event provides information about the event’s type.

  • Location and Admin2: Cramér’s V = 0.808, suggesting a moderate to strong association between the specific location of an event and its Admin2 categorization.

  • Location and Admin1: Cramér’s V = 0.722, indicating a moderate association.

Lower Associations

  • Variables like Year show generally lower associations with other variables, as indicated by lower Cramér’s V values across the board. This could imply that the year of the event is less directly related to the nature or location of the event compared to other variables.

Interpretation

The most associative features are those related to the type and subtype of events and the geographic categorizations (Admin1, Admin2, and Geographic_Area). These strong associations suggest that events are closely tied to specific locations and that the administrative and geographic categorizations are highly informative about each other.

In contrast, temporal aspects (Year) and specific actors involved (Actor1, Actor2) show weaker associations with other features, indicating these aspects of the data may be more independent or have more varied relationships with the types and locations of events.

2. Analyzing Recent News Data of Nigeria

Data exploration and cleaning:

str(news_data)
'data.frame':   1576 obs. of  19 variables:
 $ Newsfeed.Country           : chr  "Nigeria" "Nigeria" "Nigeria" "Nigeria" ...
 $ Newsfeed.Country.UNDPRegion: chr  "Africa" "Africa" "Africa" "Africa" ...
 $ Newsfeed.CountryISO        : chr  "NGA" "NGA" "NGA" "NGA" ...
 $ Newsfeed.DateDisplay       : chr  "12/3/2022 8:54" "12/3/2022 8:54" "12/3/2022 15:42" "12/3/2022 15:42" ...
 $ Newsfeed.Description       : chr  "Imo Police operatives repel attack on Orlu INEC office" "Defence Headquarters accuses Reuters of blackmail" "NRC To Resume Abuja-Kaduna Rail Operations On Monday" "NRC To Resume Abuja-Kaduna Rail Operations On Monday" ...
 $ Newsfeed.Description2      : logi  NA NA NA NA NA NA ...
 $ Newsfeed.Entity            : chr  "Electoral Commission,Eastern Security Network,Mike Abattam" "Maj.-Gen,Chibok School,Borno Government,Boko Haram,Rehabilitation Centre,Alexandra Zavis,UNICEF,Paul Julius Reu"| __truncated__ "Fidet Okhiria,Boko Haram,Railway Corporation" "Fidet Okhiria,Boko Haram,Railway Corporation" ...
 $ Newsfeed.IncidentType      : chr  "UNDP_Security" "UNDP_Security" "UNDP_Conflict" "UNDP_TerroristAttack" ...
 $ Newsfeed.Language          : chr  "English" "English" "English" "English" ...
 $ Newsfeed.Link              : chr  "https://247ureports.com/2022/12/imo-police-operatives-repel-attack-on-orlu-inec-office/" "https://247ureports.com/2022/12/defence-headquarters-accuses-reuters-of-blackmail/" "https://www.africanexaminer.com/nrc-to-resume-abuja-kaduna-rail-operations-on-monday/" "https://www.africanexaminer.com/nrc-to-resume-abuja-kaduna-rail-operations-on-monday/" ...
 $ Newsfeed.Source            : chr  "EMM" "EMM" "EMM" "EMM" ...
 $ Newsfeed.Source.Description: chr  "The freely accessible Europe Media Monitor (EMM), by the The European Commission's science and knowledge servic"| __truncated__ "The freely accessible Europe Media Monitor (EMM), by the The European Commission's science and knowledge servic"| __truncated__ "The freely accessible Europe Media Monitor (EMM), by the The European Commission's science and knowledge servic"| __truncated__ "The freely accessible Europe Media Monitor (EMM), by the The European Commission's science and knowledge servic"| __truncated__ ...
 $ Newsfeed.Source.Url        : chr  "http://emm.newsbrief.eu/NewsBrief" "http://emm.newsbrief.eu/NewsBrief" "http://emm.newsbrief.eu/NewsBrief" "http://emm.newsbrief.eu/NewsBrief" ...
 $ Newsfeed.Source2           : chr  "247ureports" "247ureports" "africanexaminer" "africanexaminer" ...
 $ Newsfeed.Trajectory        : logi  NA NA NA NA NA NA ...
 $ Date.FK                    : int  20221203 20221203 20221203 20221203 20221203 20221203 20221203 20221203 20221203 20221203 ...
 $ Newsfeed.Latitude          : num  5.8 9.06 10.53 10.53 45.41 ...
 $ Newsfeed.Longitude         : num  7.04 7.5 7.44 7.44 -75.7 ...
 $ Newsfeed.PK                : int  908 909 910 911 912 913 914 915 916 917 ...
# Convert date strings to Date objects
news_data$Newsfeed.DateDisplay <- as.POSIXct(news_data$Newsfeed.DateDisplay, format="%m/%d/%Y %H:%M")

# Remove duplicate rows based on news description and date
news_data <- news_data[!duplicated(news_data[c("Newsfeed.Description", "Newsfeed.DateDisplay")]), ]

names(news_data) <- gsub("\\.", "_", names(news_data)) # Replacing '.' with '_'

2b. Is there a key sentiment in the news?

news_data$categorized_sentiment <- sapply(news_data$Newsfeed_Description, function(description) {
  sentiment_score <- get_sentiment(description, method = "afinn")
  
  # Categorize based on sentiment score
  if (sentiment_score > 0) {
    return('Positive')
  } else if (sentiment_score < 0) {
    return('Negative')
  } else {
    return('Neutral')
  }
})

# Correcting the aggregation step
sentiments_scores <- news_data %>%
  group_by(categorized_sentiment) %>%
  summarise(count = n()) %>%
  ungroup()


soft_colors <- c("Positive" = "#A3E4D7",  # Soft Mint
                 "Neutral" = "#FAD7A0",   # Soft Peach
                 "Negative" = "#F5B7B1")  # Soft Pink

# Plot
ggplot(sentiments_scores, aes(x = categorized_sentiment, y = count, fill = categorized_sentiment)) +
  geom_bar(stat = "identity", color = "black") +
  geom_text(aes(label = count), hjust=1, vjust = 0.5) +
  coord_flip() +
  scale_fill_manual(values = soft_colors) +
  labs(title = "Sentiment Analysis of News Descriptions", x = "Sentiment", y = "Count") +
  theme_minimal() +
  theme(legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 13)),
        axis.title.x = element_text(size = 11, face = "bold"),
        axis.title.y = element_text(size = 11, face = "bold"),
        axis.text.x = element_text(size = 10, face = "bold"),
        axis.text.y = element_text(size = 10, face = "bold", color = "black"),
        plot.margin = margin(1, 1, 1, 1, "cm"))

4. Additional Analysis:

4a. Fatalities Across Different Types of Political Violence

# Aggregating fatalities by event type
fatalities_by_event_type <- political_violence %>%
  group_by(`Event_Type`) %>%
  summarise(Average_Fatalities = mean(`Fatalities`, na.rm = TRUE),
            Total_Fatalities = sum(`Fatalities`, na.rm = TRUE),
            Number_of_Events = n()) %>%
  arrange(desc(Total_Fatalities))

# Visualizing total fatalities by event type 
ggplot(fatalities_by_event_type, aes(x=reorder(Event_Type, Total_Fatalities), y=Total_Fatalities, fill=Total_Fatalities)) +
  geom_bar(stat="identity") +
  scale_fill_gradient(low = "bisque", high = "brown") + 
  geom_text(aes(label=Total_Fatalities), hjust=1.1, color="black", size=3.5) +
  coord_flip() +
  labs(title = "Total Fatalities by Event Type in Political Violence",
       x = "Event Type", y = "Total Fatalities") +
  theme_minimal() +
  theme(legend.position = "none",
        plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 13)),
        axis.title.x = element_text(size = 11, face = "bold"),
        axis.title.y = element_text(size = 11, face = "bold"),
        axis.text.x = element_text(size = 10, face = "bold"),
        axis.text.y = element_text(size = 10, face = "bold", color = "black"),
        plot.margin = margin(1, 1, 1, 1, "cm"))

print(fatalities_by_event_type)
# A tibble: 6 × 4
  Event_Type                Average_Fatalities Total_Fatalities Number_of_Events
  <chr>                                  <dbl>            <int>            <int>
1 battles                               3.90               1849              474
2 violence against civilia…             1.19                912              768
3 explosions/remote violen…             9.36                899               96
4 riots                                 0.539                97              180
5 protests                              0.0118                3              255
6 strategic developments                0                     0              129

The analysis reveals the variability of fatalities across different types of political violence in Nigeria, as follows:

  • Battles have the highest total fatalities with 1,849 fatalities across 474 events, averaging approximately 3.9 fatalities per event.

  • Violence against civilians follows with a total of 912 fatalities from 768 events, with an average of about 1.19 fatalities per event.

  • Explosions/Remote violence has a significant impact as well, with 899 total fatalities from just 96 events, indicating a much higher average fatality rate of approximately 9.36 per event.

  • Riots and Protests show lower total fatalities, with riots having 97 fatalities from 180 events and protests having the lowest impact on fatalities.

  • Strategic developments reported no fatalities across 129 events.

These findings highlight the types of political violence with the most lethal outcomes, suggesting that battles and explosions/remote violence are particularly deadly, whereas protests and strategic developments are less so.

4b. Trend of News Sentiment Over Time

news_data$Sentiment <- ifelse(nchar(as.character(news_data$`Newsfeed_Description`)) > 100, "Positive",
                             ifelse(nchar(as.character(news_data$`Newsfeed_Description`)) > 50, "Neutral", "Negative"))

news_data$YearMonth <- format(as.Date(news_data$`Newsfeed_DateDisplay`, "%m/%d/%Y"), "%Y-%m")
Warning in as.POSIXlt.POSIXct(x, tz = tz): unknown timezone '%m/%d/%Y'
# Aggregating news by YearMonth and sentiment
sentiment_over_time <- news_data %>%
  group_by(YearMonth, Sentiment) %>%
  summarise(Article_Count = n()) %>%
  spread(Sentiment, Article_Count, fill = 0) %>%
  mutate(YearMonth = as.Date(paste0(YearMonth, "-01")))
`summarise()` has grouped output by 'YearMonth'. You can override using the
`.groups` argument.
# Plotting
ggplot(sentiment_over_time, aes(x=YearMonth)) +
  geom_line(aes(y=Positive, colour="Positive")) +
  geom_line(aes(y=Neutral, colour="Neutral")) +
  geom_line(aes(y=Negative, colour="Negative")) +
  labs(title="Trend of News Sentiment Over Time", x="Time (Year-Month)", y="Number of Articles") +
  scale_colour_manual("", values=c(Positive="green", Neutral="blue", Negative="red")) +
 theme(
        plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 13)),
        axis.title.x = element_text(size = 11, face = "bold"),
        axis.title.y = element_text(size = 11, face = "bold"),
        axis.text.x = element_text(size = 10, face = "bold"),
        axis.text.y = element_text(size = 10, face = "bold", color = "black"),
        plot.margin = margin(1, 1, 1, 1, "cm"))

Key Observations:

  • The majority of news articles are categorized as negative, followed by neutral and positive articles. This distribution might reflect the predominance of negative news coverage within the dataset’s time frame.

  • There is a noticeable fluctuation in the number of articles across different months, with a significant peak in January 2023 for negative articles.

  • The number of positive and neutral articles shows less variation compared to negative articles but follows a similar trend with a slight increase in January 2023.

  • By March 2023, there’s a sharp decline in the number of news articles analyzed, indicating either a gap in the data collection or a significant reduction in news coverage.

4c. Comparison of news coverage to political violence events over the given time period.

news_data$YearMonth <- format(news_data$Newsfeed_DateDisplay, "%Y-%m")
political_violence$CreatedOn <- as.Date(political_violence$CreatedOn, "%m/%d/%Y %H:%M")
political_violence$YearMonth <- format(political_violence$CreatedOn, "%Y-%m")


news_by_month <- news_data %>%
  group_by(YearMonth) %>%
  summarise(News_Count = n()) %>%
  mutate(YearMonth = as.Date(paste0(YearMonth, "-01"))) # Convert YearMonth to Date for plotting


events_by_month <- political_violence %>%
  group_by(YearMonth) %>%
  summarise(Event_Count = n()) %>%
  mutate(YearMonth = as.Date(paste0(YearMonth, "-01"))) # Convert YearMonth to Date for plotting

comparison_df <- merge(news_by_month, events_by_month, by = "YearMonth", all = TRUE)

# Plotting
ggplot(comparison_df, aes(x = YearMonth)) +
  geom_line(aes(y = News_Count, color = "News Articles"), size = 1) +
  geom_line(aes(y = Event_Count, color = "Political Violence Events"), size = 1) +
  scale_color_manual(values = c("News Articles" = "blue", "Political Violence Events" = "green")) +
  scale_x_date(date_breaks = "1 month", date_labels = "%Y-%m") + # Control the x-axis labels
  labs(title = "Comparison of News Coverage to Political Violence Events Over Time",
       x = "Time (Year-Month)", y = "Count") +
  theme_minimal() +
  theme(legend.title = element_blank(),
        legend.position = "bottom",
        plot.title = element_text(hjust = 0.5, size = 13, face = "bold", margin = margin(b = 13)),
        axis.title.x = element_text(size = 11, face = "bold"),
        axis.title.y = element_text(size = 11, face = "bold"),
        axis.text.x = element_text(size = 10, face = "bold"),
        axis.text.y = element_text(size = 10, face = "bold", color = "black"),
        plot.margin = margin(1, 1, 1, 1, "cm"))