setwd(dirname(rstudioapi::getSourceEditorContext()$path))

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2     
## ── 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(tidylog)
## 
## Attaching package: 'tidylog'
## 
## The following objects are masked from 'package:dplyr':
## 
##     add_count, add_tally, anti_join, count, distinct, distinct_all,
##     distinct_at, distinct_if, filter, filter_all, filter_at, filter_if,
##     full_join, group_by, group_by_all, group_by_at, group_by_if,
##     inner_join, left_join, mutate, mutate_all, mutate_at, mutate_if,
##     relocate, rename, rename_all, rename_at, rename_if, rename_with,
##     right_join, sample_frac, sample_n, select, select_all, select_at,
##     select_if, semi_join, slice, slice_head, slice_max, slice_min,
##     slice_sample, slice_tail, summarise, summarise_all, summarise_at,
##     summarise_if, summarize, summarize_all, summarize_at, summarize_if,
##     tally, top_frac, top_n, transmute, transmute_all, transmute_at,
##     transmute_if, ungroup
## 
## The following objects are masked from 'package:tidyr':
## 
##     drop_na, fill, gather, pivot_longer, pivot_wider, replace_na,
##     spread, uncount
## 
## The following object is masked from 'package:stats':
## 
##     filter
library(tidytext)
library(textdata)
library(quanteda)
## Warning in .recacheSubclasses(def@className, def, env): undefined subclass
## "ndiMatrix" of class "replValueSp"; definition not updated
## Package version: 3.3.1
## Unicode version: 15.1
## ICU version: 74.1
## Parallel computing: 12 of 12 threads used.
## See https://quanteda.io for tutorials and examples.
library(quanteda.textstats)
## Warning in .recacheSubclasses(def@className, def, env): undefined subclass
## "ndiMatrix" of class "replValueSp"; definition not updated
library(quanteda.dictionaries)
library(wesanderson)
library(knitr)
library(ggplot2)

load("ventura_etal_df.Rdata")
head(ventura_etal_df)
##   text_id
## 1       1
## 2       2
## 3       3
## 4       4
## 5       5
## 6       6
##                                                                                                                                                                                                                                       comments
## 1 MORE:\n The coronavirus pandemic's impact on the race will be on display as the\n two candidates won't partake in a handshake, customary at the top of \nsuch events. The size of the audience will also be limited. https://abcn.ws/3kVyl16
## 2                                                                                                                                                           God please bless all Trump supporters. They need it for they know not what they do
## 3                                                                                                                               Trump  is  a  living  disaster!    What  an embarrassment  to  all  human  beings!    The  man  is  dangerous!
## 4                                                                                                                                                   This debate is why other counties laugh at us. School yard class president debate at best.
## 5                                                                    OMG\n ... shut up tRump ... so rude and out of control.  Obviously freaking \nout.  This is a debate NOT a convention or a speech or your platform.  \nLearn some manners
## 6                                                                                                      It’s\n hard to see what this country has become.  The Presidency is no longer a\n respected position it has lost all of it’s integrity.
##                      id likes                  debate
## 1              ABC News   100 abc_first_debate_manual
## 2            Anita Hill    61 abc_first_debate_manual
## 3          Dave Garland    99 abc_first_debate_manual
## 4              Carl Roy    47 abc_first_debate_manual
## 5 Lynda Martin-Chambers   154 abc_first_debate_manual
## 6         Nica Merchant   171 abc_first_debate_manual
tidy_ventura <- ventura_etal_df %>% 
  mutate(comments = tolower(comments)) %>% 
  unnest_tokens(word, comments) %>% 
  filter(str_detect(word, "[a-z]")) %>% 
  filter(!word %in% stop_words$word)
## mutate: changed 29,261 values (99%) of 'comments' (0 new NA)
## filter: removed 3,374 rows (1%), 494,342 rows remaining
## filter: removed 296,794 rows (60%), 197,548 rows remaining
#Question 1

dummy <- tidy_ventura %>% 
  mutate(trump_token = ifelse(word=="trump", 1, 0),
         biden_token = ifelse(word=="biden", 1, 0), 
         pence_token = ifelse(word=="pence", 1, 0),
         harris_token = ifelse(word=="harris", 1, 0)) %>% 
  group_by(text_id) %>% 
  mutate(trump_cmmnt = ifelse(sum(trump_token)>0, 1, 0),
         biden_cmmnt = ifelse(sum(biden_token)>0, 1, 0),
         pence_cmmnt = ifelse(sum(pence_token)>0, 1, 0),
         harris_cmmnt = ifelse(sum(harris_token)> 0, 1, 0)) %>% 
  distinct(text_id, .keep_all = T) %>% 
  select(text_id,trump_cmmnt,biden_cmmnt,pence_cmmnt,harris_cmmnt,likes,debate) %>% 
  ungroup() %>% 
  group_by(debate) %>% 
  mutate(total_n = n(),
         total_trump=sum(trump_cmmnt),
         total_biden=sum(biden_cmmnt),
         total_harris=sum(harris_cmmnt),
         total_pence=sum(pence_cmmnt),
         pct_trump=total_trump/total_n,
         pct_biden=total_biden/total_n,
         pct_harris=total_harris/total_n,
         pct_pence = total_pence/total_n) %>% 
  ungroup() %>% 
  distinct(debate, .keep_all=T) %>% 
  select(debate:pct_trump,pct_biden,pct_harris,pct_pence)
## mutate: new variable 'trump_token' (double) with 2 unique values and 0% NA
##         new variable 'biden_token' (double) with 2 unique values and 0% NA
##         new variable 'pence_token' (double) with 2 unique values and 0% NA
##         new variable 'harris_token' (double) with 2 unique values and 0% NA
## group_by: one grouping variable (text_id)
## mutate (grouped): new variable 'trump_cmmnt' (double) with 2 unique values and 0% NA
##                   new variable 'biden_cmmnt' (double) with 2 unique values and 0% NA
##                   new variable 'pence_cmmnt' (double) with 2 unique values and 0% NA
##                   new variable 'harris_cmmnt' (double) with 2 unique values and 0% NA
## distinct (grouped): removed 168,013 rows (85%), 29,535 rows remaining
## select: dropped 6 variables (id, word, trump_token, biden_token, pence_token, …)
## ungroup: no grouping variables
## group_by: one grouping variable (debate)
## mutate (grouped): new variable 'total_n' (integer) with 3 unique values and 0% NA
##                   new variable 'total_trump' (double) with 3 unique values and 0% NA
##                   new variable 'total_biden' (double) with 3 unique values and 0% NA
##                   new variable 'total_harris' (double) with 3 unique values and 0% NA
##                   new variable 'total_pence' (double) with 3 unique values and 0% NA
##                   new variable 'pct_trump' (double) with 3 unique values and 0% NA
##                   new variable 'pct_biden' (double) with 3 unique values and 0% NA
##                   new variable 'pct_harris' (double) with 3 unique values and 0% NA
##                   new variable 'pct_pence' (double) with 3 unique values and 0% NA
## ungroup: no grouping variables
## distinct: removed 29,532 rows (>99%), 3 rows remaining
## select: dropped 6 variables (text_id, trump_cmmnt, biden_cmmnt, pence_cmmnt, harris_cmmnt, …)
#abc

abc_debate <- dummy %>% 
  filter(debate=="abc_first_debate_manual") 
## filter: removed 2 rows (67%), one row remaining
abc_debate_long <- pivot_longer(abc_debate,
                                cols=starts_with("pct_"),
                                names_to="candidate",
                                values_to = "percentage",
                                names_prefix="pct_")
## pivot_longer: reorganized (pct_trump, pct_biden, pct_harris, pct_pence) into (candidate, percentage) [was 1x10, now 4x8]
#nbc

nbc_debate <- dummy %>% 
  filter(debate=="nbc_first_debate_manual")
## filter: removed 2 rows (67%), one row remaining
nbc_debate_long <- pivot_longer(nbc_debate,
                                cols=starts_with("pct"),
                                names_to="candidate",
                                values_to = "percentage",
                                names_prefix="pct")
## pivot_longer: reorganized (pct_trump, pct_biden, pct_harris, pct_pence) into (candidate, percentage) [was 1x10, now 4x8]
#fox

fox_debate <- dummy %>% 
  filter(debate=="fox_first_debate_manual")
## filter: removed 2 rows (67%), one row remaining
fox_debate_long <- pivot_longer(fox_debate,
                                cols=starts_with("pct"),
                                names_to="candidate",
                                values_to="percentage",
                                names_prefix="pct")
## pivot_longer: reorganized (pct_trump, pct_biden, pct_harris, pct_pence) into (candidate, percentage) [was 1x10, now 4x8]
#plotting abc, nbc, fox debates

abc_debate_long %>% 
  ggplot(aes(x=candidate, y=percentage)) +
  geom_col(alpha=0.6) +
  coord_flip() +
  theme_minimal() +
  labs(x="Debate", y="% of Comments Mentioning a Candidate") 

nbc_debate_long %>% 
  ggplot(aes(x=candidate, y=percentage)) +
  geom_col(alpha=0.6) +
  coord_flip() +
  theme_minimal() +
  labs(x="Debate", y="% of Comments Mentioning a Candidate")

fox_debate_long %>% 
  ggplot(aes(x=candidate, y=percentage)) +
  geom_col(alpha=0.6) +
  coord_flip() +
  theme_minimal() +
  labs(x="Debate", y="% of Comments Mentioning a Candidate") 

#combining everything into one plot

abc_debate_long <- abc_debate_long %>% mutate(debate = "ABC")
## mutate: changed 4 values (100%) of 'debate' (0 new NA)
nbc_debate_long <- nbc_debate_long %>% mutate(debate = "NBC")
## mutate: changed 4 values (100%) of 'debate' (0 new NA)
fox_debate_long <- fox_debate_long %>% mutate(debate = "FOX")
## mutate: changed 4 values (100%) of 'debate' (0 new NA)
combined_debate <- bind_rows(abc_debate_long, nbc_debate_long, fox_debate_long)

ggplot(combined_debate, aes(x=candidate, y=percentage)) +
  geom_col(alpha=0.6) +
  coord_flip() +
  theme_minimal() +
  facet_wrap(~debate, scales = "free_y") +
  labs(x="Debate", y="% of Comments Mentioning a Candidate")

#good enough i think. im too stupid to arrange this the way the author did so :/


##Problem 2:

corpus_ventura <- corpus(ventura_etal_df,
                         text_field="comments",
                         unique_docnames=TRUE)
toks_ventura <- tokens(corpus_ventura)
kw_BIden <- kwic(toks_ventura, pattern="Biden")
head(kw_BIden, 20)
## Keyword-in-context with 20 matches.                                                       
##   [text16, 1]                                 | Biden |
##   [text18, 1]                                 | Biden |
##   [text21, 1]                                 | Biden |
##   [text25, 2]                              If | Biden |
##  [text27, 32]         both sides equally. Let | Biden |
##   [text29, 4]                   Thank you Joe | Biden |
##   [text38, 8]        not being fair he favors | Biden |
##  [text38, 18]     President to even speak and | Biden |
##   [text40, 7] only wants to personally attack | Biden |
##   [text53, 2]                             Joe | Biden |
##  [text54, 16]        values will vote for Joe | Biden |
##   [text67, 2]                          Voting | Biden |
##  [text71, 16]          trying to separate us. | Biden |
##   [text75, 1]                                 | Biden |
##  [text83, 11]        can't shut-up, can't let | Biden |
##   [text84, 1]                                 | Biden |
##   [text85, 1]                                 | Biden |
##   [text87, 2]                              If | Biden |
##   [text90, 4]                      I love how | Biden |
##  [text101, 2]                             Joe | Biden |
##                                 
##  handled this SO much better    
##  is right Trump doesn’t have    
##  is too much of a               
##  was going to do all            
##  talk. geeze.                   
##  for your composure and the     
##  and doesn’t allow the President
##  breaks into trumps speaking all
##  because he doesn't have the    
##  needs to stop calling President
##  !!                             
##  / Harris because we deserve    
##  is right. We must              
##  is talking to us while         
##  speak! I'm frustrated!         
##  all the way. We                
##  can't finish a sentence,       
##  would quit lying Trump wouldn't
##  laughs at childish and ignorant
##  act more like a president
ventura_lowercase <- ventura_etal_df %>% 
  mutate(comments=tolower(comments))
## mutate: changed 29,261 values (99%) of 'comments' (0 new NA)
corpus_ventura_lowercase <- corpus(ventura_lowercase,
                                   text_field = "comments",
                                   unique_docnames = TRUE)
toks_ventura <- tokens(corpus_ventura)
kw_Biden2 <- kwic(toks_ventura, pattern="Biden")
head(kw_Biden2, 20)
## Keyword-in-context with 20 matches.                                                       
##   [text16, 1]                                 | Biden |
##   [text18, 1]                                 | Biden |
##   [text21, 1]                                 | Biden |
##   [text25, 2]                              If | Biden |
##  [text27, 32]         both sides equally. Let | Biden |
##   [text29, 4]                   Thank you Joe | Biden |
##   [text38, 8]        not being fair he favors | Biden |
##  [text38, 18]     President to even speak and | Biden |
##   [text40, 7] only wants to personally attack | Biden |
##   [text53, 2]                             Joe | Biden |
##  [text54, 16]        values will vote for Joe | Biden |
##   [text67, 2]                          Voting | Biden |
##  [text71, 16]          trying to separate us. | Biden |
##   [text75, 1]                                 | Biden |
##  [text83, 11]        can't shut-up, can't let | Biden |
##   [text84, 1]                                 | Biden |
##   [text85, 1]                                 | Biden |
##   [text87, 2]                              If | Biden |
##   [text90, 4]                      I love how | Biden |
##  [text101, 2]                             Joe | Biden |
##                                 
##  handled this SO much better    
##  is right Trump doesn’t have    
##  is too much of a               
##  was going to do all            
##  talk. geeze.                   
##  for your composure and the     
##  and doesn’t allow the President
##  breaks into trumps speaking all
##  because he doesn't have the    
##  needs to stop calling President
##  !!                             
##  / Harris because we deserve    
##  is right. We must              
##  is talking to us while         
##  speak! I'm frustrated!         
##  all the way. We                
##  can't finish a sentence,       
##  would quit lying Trump wouldn't
##  laughs at childish and ignorant
##  act more like a president
corpus_ventura_processed <- tokens(corpus_ventura_lowercase,
                                   remove_numbers = TRUE,
                                   remove_punct = TRUE,
                                   remove_url = TRUE,
                                   remove_symbols = TRUE,
                                   remove_separators = TRUE)
corpus_ventura_processed <- tokens_remove(corpus_ventura_processed,
                                          c(stopwords(language="en")),
                                          padding=F)
tokens_tolower(corpus_ventura_processed, keep_acronyms = FALSE)
## Tokens consisting of 29,547 documents and 4 docvars.
## text1 :
##  [1] "coronavirus" "pandemic's"  "impact"      "race"        "display"    
##  [6] "two"         "candidates"  "partake"     "handshake"   "customary"  
## [11] "top"         "events"     
## [ ... and 4 more ]
## 
## text2 :
## [1] "god"        "please"     "bless"      "trump"      "supporters"
## [6] "need"       "know"      
## 
## text3 :
## [1] "trump"         "living"        "disaster"      "embarrassment"
## [5] "human"         "beings"        "man"           "dangerous"    
## 
## text4 :
##  [1] "debate"    "counties"  "laugh"     "us"        "school"    "yard"     
##  [7] "class"     "president" "debate"    "best"     
## 
## text5 :
##  [1] "omg"        "shut"       "trump"      "rude"       "control"   
##  [6] "obviously"  "freaking"   "debate"     "convention" "speech"    
## [11] "platform"   "learn"     
## [ ... and 1 more ]
## 
## text6 :
##  [1] "it’s"       "hard"       "see"        "country"    "become"    
##  [6] "presidency" "longer"     "respected"  "position"   "lost"      
## [11] "it’s"       "integrity" 
## 
## [ reached max_ndoc ... 29,541 more documents ]
kw_Biden_processed <- kwic(corpus_ventura_processed, pattern="Biden")

head(kw_Biden_processed, 20)
## Keyword-in-context with 20 matches.                                                          
##   [text16, 1]                                    | biden |
##   [text18, 1]                                    | biden |
##   [text21, 1]                                    | biden |
##   [text25, 1]                                    | biden |
##  [text27, 14]       wanna hear sides equally let | biden |
##   [text29, 3]                          thank joe | biden |
##   [text38, 4]                 wallis fair favors | biden |
##  [text38, 10] doesn’t allow president even speak | biden |
##   [text40, 5]      trump wants personally attack | biden |
##   [text53, 2]                                joe | biden |
##  [text54, 10]     loves american values vote joe | biden |
##   [text67, 2]                             voting | biden |
##  [text71, 11]  party steadily trying separate us | biden |
##   [text75, 1]                                    | biden |
##   [text83, 6]    trump stop bullying shut-up let | biden |
##   [text84, 1]                                    | biden |
##   [text85, 1]                                    | biden |
##   [text87, 1]                                    | biden |
##   [text90, 2]                               love | biden |
##  [text101, 2]                                joe | biden |
##                                                  
##  handled much better trump wasn’t                
##  right trump doesn’t plan healthcare             
##  much gentleman bring trumps trashy              
##  going great things lord knows                   
##  talk geeze                                      
##  composure dignity bring debate                  
##  doesn’t allow president even speak              
##  breaks trumps speaking time                     
##  intelligence respect process accomplished giving
##  needs stop calling president names              
##                                                  
##  harris deserve true presidential leadership     
##  right must come together stand                  
##  talking us trump trying argue                   
##  speak frustrated                                
##  way need change need make                       
##  finish sentence cause trump stop                
##  quit lying trump interrupt trump                
##  laughs childish ignorant trump                  
##  act like president trump tonight
head(kw_BIden,20)
## Keyword-in-context with 20 matches.                                                       
##   [text16, 1]                                 | Biden |
##   [text18, 1]                                 | Biden |
##   [text21, 1]                                 | Biden |
##   [text25, 2]                              If | Biden |
##  [text27, 32]         both sides equally. Let | Biden |
##   [text29, 4]                   Thank you Joe | Biden |
##   [text38, 8]        not being fair he favors | Biden |
##  [text38, 18]     President to even speak and | Biden |
##   [text40, 7] only wants to personally attack | Biden |
##   [text53, 2]                             Joe | Biden |
##  [text54, 16]        values will vote for Joe | Biden |
##   [text67, 2]                          Voting | Biden |
##  [text71, 16]          trying to separate us. | Biden |
##   [text75, 1]                                 | Biden |
##  [text83, 11]        can't shut-up, can't let | Biden |
##   [text84, 1]                                 | Biden |
##   [text85, 1]                                 | Biden |
##   [text87, 2]                              If | Biden |
##   [text90, 4]                      I love how | Biden |
##  [text101, 2]                             Joe | Biden |
##                                 
##  handled this SO much better    
##  is right Trump doesn’t have    
##  is too much of a               
##  was going to do all            
##  talk. geeze.                   
##  for your composure and the     
##  and doesn’t allow the President
##  breaks into trumps speaking all
##  because he doesn't have the    
##  needs to stop calling President
##  !!                             
##  / Harris because we deserve    
##  is right. We must              
##  is talking to us while         
##  speak! I'm frustrated!         
##  all the way. We                
##  can't finish a sentence,       
##  would quit lying Trump wouldn't
##  laughs at childish and ignorant
##  act more like a president
#I believe that the unprocessed/pre-processed approach provides more info about
#the context in which Biden's name appears in the comments. this is because there is really
#a lack of flow and the words are pulled out of context which leaves the reader, aka me, with
#little to no idea what the commenter actually thinks of good old sleepy joe. 


#Question 3:

#pre-processed


toks_ventura <- tokens(corpus_ventura)
col_ventura <- tokens_select(toks_ventura) %>% 
  textstat_collocations(min_count = 20)

head(col_ventura, 20)
##        collocation count count_nested length   lambda         z
## 1    chris wallace  1764            0      2 7.175830 125.49663
## 2            🇺🇸 🇺🇸   917            0      2 8.416407  94.70749
## 3              😂 😂   578            0      2 7.749490  85.87535
## 4         trump is  1982            0      2 2.303882  85.21253
## 5          shut up   474            0      2 5.757830  81.97666
## 6  president trump   911            0      2 3.341972  81.26495
## 7       wallace is  1208            0      2 2.938571  79.80890
## 8          this is  1359            0      2 2.575673  77.89669
## 9        should be   505            0      2 4.614114  77.05604
## 10     our country   435            0      2 4.775768  76.56377
## 11     this debate   686            0      2 3.587787  76.19566
## 12             🤣 🤣   502            0      2 8.794778  75.99899
## 13        fox news   323            0      2 7.507495  74.12384
## 14           he is  1643            0      2 2.126982  73.47883
## 15           to be  1016            0      2 2.787355  71.39251
## 16            is a  1668            0      2 1.962096  69.11858
## 17          out of   503            0      2 4.121909  68.55492
## 18   talking about   350            0      2 5.277457  68.43779
## 19             ❤ ❤   270            0      2 8.045745  68.13917
## 20    this country   501            0      2 3.834727  67.99850
#processed


toks_ventura2 <- tokens(corpus_ventura_processed, 
                        remove_punct=TRUE,
                        remove_symbols = TRUE,
                        remove_numbers = TRUE,
                        remove_separators = TRUE,
                        remove_url = TRUE,
                        c(stopwords(language = "en"), "now"), padding = F)

col_ventura2 <- tokens_select(toks_ventura2,
                              pattern = "^[A-Z]",
                              valuetype="regex",
                              case_insensitive = FALSE,
                              padding=TRUE) %>% 
  textstat_collocations(min_count=30)
head(col_ventura2, 20)
## [1] collocation  count        count_nested length       lambda      
## [6] z           
## <0 rows> (or 0-length row.names)
colls <- textstat_collocations(toks_ventura2)
head(colls, 20)
##         collocation count count_nested length   lambda         z
## 1     chris wallace  1806            0      2 6.098530 116.86726
## 2             🇺🇸 🇺🇸  1001            0      2 8.613118  77.58677
## 3          fox news   380            0      2 6.723614  70.99652
## 4   president trump   992            0      2 2.278421  59.66708
## 5   american people   288            0      2 4.982640  54.90888
## 6         joe biden   498            0      2 2.584771  48.88443
## 7   answer question   140            0      2 5.165578  47.76737
## 8    climate change   158            0      2 8.521726  46.23422
## 9        can’t even   168            0      2 4.269098  46.00813
## 10     mail ballots    93            0      2 6.393349  44.02194
## 11 answer questions   118            0      2 4.831912  42.93656
## 12        ever seen   102            0      2 6.155389  42.90370
## 13      health care   114            0      2 6.504349  41.86609
## 14        right now   116            0      2 4.646811  41.62729
## 15       every time   129            0      2 4.451515  41.26157
## 16    united states   168            0      2 9.003083  41.16077
## 17        pay taxes    97            0      2 5.212219  40.62668
## 18         year old    74            0      2 6.452707  40.50508
## 19     mr president   197            0      2 3.869622  39.21961
## 20       obama care   106            0      2 4.485620  39.13649
#comparing the processed and pre-procssed version tells us that there are some words
#that appear together on a consistent basis (i.e.: chris wallace).
#the fact that they appear together when analyzing the two corpi for collocation means
#that there is a robust relationship between the words. the processed version gets rid of any
#noise 

#the processed version offers a better picture of the corpi. 
#the processed version also tells us more as it removes stop words, which is important as
#these words could potentially skew the data when conducting further analysis. the processed
#corpus also reveals words that are collocated that the pre-procssed does not. for instance 
#mail ballots

#in telling us more about which words are associated with trump/biden and in illustrating
#the sentiments attached to them and the sentiments of the comments overall. in other words
#stop words are not insightful and are "fluffing" up the data 

#Question 4

bing <- get_sentiments("bing")

comment_analysis <- tidy_ventura %>%
  left_join(bing, by = "word") %>%
  mutate(
    pos_dum = as.integer(sentiment == "positive"),
    neg_dum = as.integer(sentiment == "negative"),
    trump_token = as.integer(word == "trump"),
    biden_token = as.integer(word == "biden")) %>%
  group_by(text_id) %>%
  summarise(
    total_pos = sum(pos_dum, na.rm = TRUE),
    total_neg = sum(neg_dum, na.rm = TRUE),
    trump_cmmnt = max(trump_token),
    biden_cmmnt = max(biden_token),
    total_words = n(),
    .groups = 'drop')
## left_join: added one column (sentiment)
##            > rows only in x   153,612
##            > rows only in y  (  4,674)
##            > matched rows      43,937    (includes duplicates)
##            >                 =========
##            > rows total       197,549
## mutate: new variable 'pos_dum' (integer) with 3 unique values and 78% NA
##         new variable 'neg_dum' (integer) with 3 unique values and 78% NA
##         new variable 'trump_token' (integer) with 2 unique values and 0% NA
##         new variable 'biden_token' (integer) with 2 unique values and 0% NA
## group_by: one grouping variable (text_id)
## summarise: now 29,535 rows and 6 columns, ungrouped
unique_metadata <- tidy_ventura %>%
  select(text_id, likes, debate) %>%
  distinct()
## select: dropped 2 variables (id, word)
## distinct: removed 168,013 rows (85%), 29,535 rows remaining
comment_analysis <- comment_analysis %>%
  left_join(unique_metadata, by = "text_id")
## left_join: added 2 columns (likes, debate)
##            > rows only in x        0
##            > rows only in y  (     0)
##            > matched rows     29,535
##            >                 ========
##            > rows total       29,535
avg_prop_pos_trump <- comment_analysis %>%
  filter(trump_cmmnt == 1) %>%
  summarise(avg_prop = mean(total_pos / total_words, na.rm = TRUE)) %>%
  pull(avg_prop)
## filter: removed 18,944 rows (64%), 10,591 rows remaining
## summarise: now one row and one column, ungrouped
avg_prop_pos_biden <- comment_analysis %>%
  filter(biden_cmmnt == 1) %>%
  summarise(avg_prop = mean(total_pos / total_words, na.rm = TRUE)) %>%
  pull(avg_prop)
## filter: removed 22,330 rows (76%), 7,205 rows remaining
## summarise: now one row and one column, ungrouped
#printing the results
cat("Average Proportion of Positive Words for Trump Comments:", avg_prop_pos_trump, "\n")
## Average Proportion of Positive Words for Trump Comments: 0.2246126
cat("Average Proportion of Positive Words for Biden Comments:", avg_prop_pos_biden, "\n")
## Average Proportion of Positive Words for Biden Comments: 0.09522671
#average trump positive comments = 0.22
#average biden positive comments = 0.09
#trump is getting more love than Biden on average. Not even surprised.

#afinn time lets goooo

afinn <- get_sentiments("afinn") 

afinn_positive <- afinn %>% 
  filter(value > 0) 
## filter: removed 1,599 rows (65%), 878 rows remaining
ventura_positive <- tidy_ventura %>% 
  left_join(afinn_positive, by="word") 
## left_join: added one column (value)
##            > rows only in x   185,239
##            > rows only in y  (    440)
##            > matched rows      12,309
##            >                 =========
##            > rows total       197,548
ventura_positive <- ventura_positive %>% 
  mutate(trump_mention=ifelse(grepl("trump", word, ignore.case=TRUE), 1, 0), 
         biden_mention=ifelse(grepl("biden", word, ignore.case=TRUE), 1, 0)) %>% 
  group_by(text_id) %>%  
  summarise(trump_cmmnt=max(trump_mention), 
            biden_cmmnt=max(biden_mention),
            avg_positive_sentiment = mean(value, na.rm=TRUE),
            .groups = 'drop') 
## mutate: new variable 'trump_mention' (double) with 2 unique values and 0% NA
##         new variable 'biden_mention' (double) with 2 unique values and 0% NA
## group_by: one grouping variable (text_id)
## summarise: now 29,535 rows and 4 columns, ungrouped
avg_positive_sentiment_trump <- ventura_positive %>% 
  filter(trump_cmmnt == 1) %>% 
  summarise(average=mean(avg_positive_sentiment, na.rm=TRUE)) 
## filter: removed 18,111 rows (61%), 11,424 rows remaining
## summarise: now one row and one column, ungrouped
avg_positive_sentiment_biden <- ventura_positive %>% 
  filter(biden_cmmnt == 1) %>% 
  summarise(average = mean(avg_positive_sentiment, na.rm=TRUE)) 
## filter: removed 21,947 rows (74%), 7,588 rows remaining
## summarise: now one row and one column, ungrouped
print(avg_positive_sentiment_trump) 
## # A tibble: 1 × 1
##   average
##     <dbl>
## 1    2.09
print(avg_positive_sentiment_biden) 
## # A tibble: 1 × 1
##   average
##     <dbl>
## 1    2.07
#both trump and biden have a similar positive sentiment on average among their
#supposed supporters. biden ranks slightly lower, however, with an average sentiment of
#2.07 as opposed to trump's 2.09

#Question 5 

#Partially answered in Question 4 so I will take some liberties here

comment_analysis2 <- comment_analysis %>% 
  left_join(tidy_ventura %>% 
              select(text_id, likes, debate) %>%  
              distinct(), by = "text_id") 
## select: dropped 2 variables (id, word)
## distinct: removed 168,013 rows (85%), 29,535 rows remaining
## left_join: added 4 columns (likes.x, debate.x, likes.y, debate.y)
##            > rows only in x        0
##            > rows only in y  (     0)
##            > matched rows     29,535
##            >                 ========
##            > rows total       29,535
#Mean net tone approach

net_tone <- comment_analysis2 %>% 
  mutate(net_tone_trump = ifelse(trump_cmmnt==1, (total_pos - total_neg)/total_words, NA),
         net_tone_biden = ifelse(biden_cmmnt==1, (total_pos - total_neg)/total_words, NA))
## mutate: new variable 'net_tone_trump' (double) with 110 unique values and 64% NA
##         new variable 'net_tone_biden' (double) with 106 unique values and 76% NA
mean_net_tone_trump <- mean(net_tone$net_tone_trump, na.rm=TRUE)
mean_net_tone_trump 
## [1] 0.1121549
mean_net_tone_biden <- mean(net_tone$net_tone_biden, na.rm=TRUE) 
mean_net_tone_biden
## [1] -0.008938341
#trump's mean tone is 0.112 whereas biden's is -0.0089. people talk about trump in a 
#better tone, whereas biden comments are more negatively connotated. 

#Ratio approach

ratio_dn <- comment_analysis2 %>% 
  mutate(ratio_trump = ifelse(trump_cmmnt == 1, (total_pos - total_neg)/(total_pos + total_neg), NA),
         ratio_biden = ifelse(biden_cmmnt == 1, (total_pos - total_neg)/(total_pos + total_neg), NA)) 
## mutate: new variable 'ratio_trump' (double) with 28 unique values and 64% NA
##         new variable 'ratio_biden' (double) with 25 unique values and 81% NA
mean_ratio_trump <- mean(ratio_dn$ratio_trump == 1, na.rm = TRUE) 
mean_ratio_trump
## [1] 0.4731376
mean_ratio_biden <- mean(ratio_dn$ratio_biden == 1, na.rm = TRUE)
mean_ratio_biden
## [1] 0.3088526
#trump's mean ratio is 0.47 while biden's is 0.3088 with respect to positive-negative ratio
#for comments

#Toxicity Analysis 

toxic_by_britney_spears.mp3 <- comment_analysis2 %>% 
  mutate(toxicity_trump = ifelse(trump_cmmnt==1, (total_neg/total_words), NA),
         toxicity_biden = ifelse(biden_cmmnt==1, (total_neg/total_words), NA))
## mutate: new variable 'toxicity_trump' (double) with 66 unique values and 64% NA
##         new variable 'toxicity_biden' (double) with 65 unique values and 76% NA
mean_toxicity_trump <- mean(toxic_by_britney_spears.mp3$toxicity_trump, na.rm = TRUE)
mean_toxicity_trump
## [1] 0.1124577
mean_toxicity_biden <- mean(toxic_by_britney_spears.mp3$toxicity_biden, na.rm = TRUE)
mean_toxicity_biden
## [1] 0.104165
#Question 6:

fares_dictionary_is_so_awesome <- cbind.data.frame(c("elect", "vote", "democracy", "ballot",
                                                     "caucus", "majority", "absentee", "voter",
                                                     "jerrymandering", "nomination", "polls", "poll"),
                                                   "elections") 

colnames(fares_dictionary_is_so_awesome) <- c("word", "topic")
dict <- rbind.data.frame(fares_dictionary_is_so_awesome)
dict
##              word     topic
## 1           elect elections
## 2            vote elections
## 3       democracy elections
## 4          ballot elections
## 5          caucus elections
## 6        majority elections
## 7        absentee elections
## 8           voter elections
## 9  jerrymandering elections
## 10     nomination elections
## 11          polls elections
## 12           poll elections
ventura_lmeow <- tidy_ventura %>% 
  left_join(dict)
## Joining with `by = join_by(word)`
## left_join: added one column (topic)
## > rows only in x 195,876
## > rows only in y ( 1)
## > matched rows 1,672
## > =========
## > rows total 197,548
ventura_lmeow %>% 
  filter(!is.na(topic)) %>% 
  group_by(topic) %>% 
  count(word, sort = TRUE)
## filter: removed 195,876 rows (99%), 1,672 rows remaining
## group_by: one grouping variable (topic)
## count: now 11 rows and 3 columns, one group variable remaining (topic)
## # A tibble: 11 × 3
## # Groups:   topic [1]
##    topic     word           n
##    <chr>     <chr>      <int>
##  1 elections vote        1188
##  2 elections ballot       146
##  3 elections polls         79
##  4 elections voter         66
##  5 elections majority      49
##  6 elections democracy     41
##  7 elections absentee      38
##  8 elections poll          31
##  9 elections elect         21
## 10 elections nomination    12
## 11 elections caucus         1
dict <- dictionary(list(elections = c("elect*", "vot*", "democra*", "ballot*", "caucus*", "majorit*",
                                      "absente*", "jerrymander*", "nominat*", "poll*")))

ventura_lmeow <- liwcalike(ventura_etal_df$comments, dictionary = dict)
topics <- cbind.data.frame(ventura_etal_df, ventura_lmeow)
head(topics[topics$elections>0,])
##    text_id
## 11      11
## 16      16
## 27      27
## 47      47
## 54      54
## 55      55
##                                                                                                                                                            comments
## 11  with\n the usa having such a bad opiate problem then trump brings up about \nbidens son is the most disgraceful thing any human being could do...vote\n him out
## 16                                    Biden handled this SO much better than Trump and I wasn’t even going to vote for him. Looks like I might be changing my mind.
## 27 what\n a headache debate.  for once, i wish trump would shut his trap for \nonce.  as a middle voter, i wanna hear both sides equally. Let Biden \ntalk.  geeze.
## 47                                                                          America need not analyze this mess of a President and this 'debate', just VOTE HIM OUT!
## 54                                                                       Anyone who is truly American and lives and loves American values will vote for Joe Biden!!
## 55                                                                                  My 7 year old said she’s voting for herself. I think I will vote for her also!😁
##                           id likes                  debate docname Segment
## 11               Lynn Kohler    41 abc_first_debate_manual  text11      11
## 16        Shelby Kaye McPike    31 abc_first_debate_manual  text16      16
## 27                 LeAnn Kim    71 abc_first_debate_manual  text27      27
## 47 Sekeywi Simone Carruthers    31 abc_first_debate_manual  text47      47
## 54               Moke Hodzic    22 abc_first_debate_manual  text54      54
## 55   Theresa Ingram Olugbile    22 abc_first_debate_manual  text55      55
##          WPS WC Sixltr   Dic elections AllPunc Period Comma Colon SemiC QMark
## 11 32.000000 32   6.25  3.12      3.12    9.38   9.38  0.00     0     0     0
## 16 13.500000 27   7.41  3.70      3.70   11.11   7.41  0.00     0     0     0
## 27 18.000000 36   5.56  2.78      2.78   19.44  13.89  5.56     0     0     0
## 47 20.000000 20  15.00  5.00      5.00   20.00   0.00  5.00     0     0     0
## 54 18.000000 18  11.11  5.56      5.56   11.11   0.00  0.00     0     0     0
## 55  6.666667 20   5.00 10.00     10.00   15.00   5.00  0.00     0     0     0
##    Exclam Dash Quote Apostro Parenth OtherP
## 11   0.00    0   0.0     0.0       0   9.38
## 16   0.00    0   3.7     3.7       0   7.41
## 27   0.00    0   0.0     0.0       0  19.44
## 47   5.00    0  10.0    10.0       0  20.00
## 54  11.11    0   0.0     0.0       0  11.11
## 55   5.00    0   5.0     5.0       0  10.00
#some limitations/issues with my dictionary include the fact that a) it is a small sample
#and as a result, it might not capture the full range of comments that are applied wrt to
#either candidate or their party. b) words like elect*, vot*, democra* may not tell us much
#about what is being said and why/how as these words could apply to either candidate and their party
#c) there is also the issue of whether or not these stemmed words even apply to the topic of 
#presidential elections. majorit* could apply to majoritarian systems of government and vot* 
#could apply to votary and not voter.