-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.Rmd
883 lines (444 loc) · 30.4 KB
/
index.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
---
title: "Querying Twitter API Data"
subtitle: "System Investigation Project"
author: "Hannah Luebbering"
date: "May 20, 2022"
output:
html_document:
toc: yes
toc_float: yes
css: "assets/main.css"
# knit: pagedown::chrome_print
knit: (function(inputFile, encoding) {rmarkdown::render(inputFile, encoding = encoding, output_dir = "docs") })
bibliography: "assets/references.bib"
nocite: "@*"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE, fig.align = "center",out.width = "95%")
library(dplyr)
library(twitteR)
library(tidyverse)
library(kableExtra)
library(lubridate)
library(scales)
library(tidyr)
library(ggplot2)
library(tidytext)
library(quanteda)
library(hrbrthemes)
library(httr)
library(devtools)
library(plyr)
library(readr)
library(plotly)
library(rtweet)
library(syuzhet)
library(textfeatures)
library(gridExtra)
library(patchwork)
library(ggpubr)
library(pagedown)
library(packcircles)
library(magick)
library(gt)
library(gtExtras)
library(paletteer)
source("scripts/data.R")
source("scripts/sentiment.R")
```
<script src="assets/min.js"></script>
<script src="assets/min.r.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
## Introduction
<span class="myhighlight">Overview:</span> The following project aims to programmatically retrieve and analyze all of Elon Musk's tweets from the Twitter API. We compile over 10,000 of Musk's tweets into a comprehensive dataset and perform sentiment analysis for each tweet object.
```{r, out.width="90%"}
htmltools::includeHTML("assets/kable_out.html")
```
```{r, eval=FALSE}
userDF %>% dplyr::select(-description, -name, -favourites_count) %>%
dplyr::mutate(account_created_at = as_date(account_created_at)) %>%
kable(escape = F, align = "c") %>%
kable_styling(font_size = 12, full_width = T, html_font = "Roboto Condensed", bootstrap_options = c("hover", "striped")) %>%
row_spec(0, font_size = 11) %>%
scroll_box(width = "100%", extra_css = "overflow-x: overlay !important; border: none !important; margin: 12pt 0px 12pt 0;")
```
Elon Musk, who transformed the electric car industry and accelerated the world's space exploration efforts, provides the public an unfiltered look into his eccentric mind through his online Twitter presence. With more than 77 million followers, Musk is one of the most followed Twitter accounts, with each of his tweets getting thousands of shares, likes, and comments. Musk tweets frequently every day, covering a wide range of topics from technical ideas to lighthearted memes. Some of his tweets have a significant impact, making headlines, instigating controversy, and sometimes pushing the needle on everything from Tesla's stock price to cryptocurrency markets. The companies that Musk runs are also hugely influential and disruptive.
To better understand Musk's Twitter profile, we programmatically retrieve and analyze all of Elon Musk's tweets using the `rtweet` package, which provides a convenient interface between the Twitter API and R code. We compiled over 10,000 of his tweets into a comprehensive dataset. Once we scraped a decade worth of Elon Musk tweets, we analyzed the data and sorted the information to answer the following questions.
<div class = "datasource2">
1. `(tweet types)` What is the ratio of mentions, replies, retweets, quotes, and organic tweets?
2. `(user engagement)` How does Elon Musk engage with other twitter users?
3. `(twitter activity)` Are there any trends of when Musk tweets?
4. `(topics)` What are Elon Musk’s most tweeted topics?
</div>
------------------------------------
## Data Description
Using the Twitter API, we compile over 10,000 of Musk's tweets into a comprehensive dataset. The dataset contains all of Elon Musk's tweets from 2015 to 2022, stored in RDS format, where each tweet is in its separate row object. All Tweets are collected, parsed, and plotted using <code>rtweet</code> in R.
```{r}
kable(dfvar, escape = FALSE, col.names = NULL) %>% kable_styling(font_size = 12, bootstrap_options = c("striped", "hover"), html_font = "Roboto Condensed") %>%
column_spec(c(1, 3, 5, 7), extra_css = c("font-weight: 700; font-family: Roboto; font-size: 13.5px; text-shadow: 0 1px 1px white, 0.04em 0.04em 0px #0000004d;"), width_max = "1cm") %>%
add_header_above(c("Data Set Variables" = 8), align = "l", extra_css = c("text-transform: uppercase; text-shadow: 0 1px 1px white, 0.04em 0.04em 0px #0000004d;"), font_size = 12) %>% scroll_box(width = "100%", extra_css = "overflow-x: overlay !important; border: none !important; margin: 12pt 0px 12pt 0;")
```
### Twitter API
To get the data for the Twitter account, we must first register a developer account and create an application with the necessary credentials to access the Twitter API. After setting up the application, we generate an authentication key and use the following commands to create a Twitter token that allows access to Twitter data.
```{r, echo=TRUE, eval=FALSE}
library(rtweet) # load rtweet package
twitter_token <- create_token(app = "twitter_app", consumer_key = "api_key", consumer_secret = "api_secret", access_token = "access_token", access_secret = "access_secret")
use_oauth_token(twitter_token) # authenticate via web browser
```
Searching Twitter's full archive API with the `rtweet` package, we run the `search_fullarchive()` function to access and extract the complete historical information of all the tweets associated with a particular user. We can then save these excerpted tweets to an RDS file. The sample code below captures Elon Musk's tweets from January 01, 2010, to May 28, 2022.
```{r, echo=TRUE, eval=FALSE}
df <- search_fullarchive(q = "from:elonmusk", n = 10000, env_name = enviroment_name, fromDate = "201001010000", toDate = "202205280000")
```
```{r}
tweetDF2 <- tweetDF %>% select(-status_id, -symbols, -source, -hashtags, -media_type)
kable(tweetDF2, escape = F) %>%
kable_styling(font_size = 13, html_font = "Roboto Condensed", bootstrap_options = c("striped")) %>%
column_spec(c(3:9), width_max = "2.5cm", extra_css = c("font-size: 11px;")) %>%
column_spec(1, extra_css = c("font-size: 11.25px;"), width_min = "2cm") %>%
row_spec(0, extra_css = c("font-weight: 700; font-size: 11px;")) %>%
add_header_above(c("Data Set Preview:" = 9), align = "l",
extra_css = c("font-weight: 400; letter-spacing: 0.25px; text-transform: uppercase; color: #1d9bf0; font-size: 9pt; text-shadow: 0.15px 0.15px 0.001px #12121240, -0.25px -0.25px 0.2px #d1d6e0f2, 0.25px 0.25px 0.25px #00000080, -0.2px -0.2px 0.1px #1a1a1a40, -0.5px -0.5px 0.2px #e6e6e680, 0.5px 0.5px 0.5px #b3b3b380; text-align: left;")) %>%
scroll_box(width = "100%", extra_css = "overflow-x: overlay !important; border: none !important; margin: 12pt 0px 12pt 0;")
```
#### Storing Data in Databricks
Optionally, we can load the Twitter API data into a data management system, such as Azure Databricks, and write queries to run a SQL job and retrieve the data. From the Azure portal, we create and launch a Databricks workspace, establish a Spark cluster, and configure a notebook on the cluster. In the notebook, we use **SparkR** to read the dataset into a Spark DataFrame and run a SQL job to query the data.
`Azure Databricks` is an analytics platform based on Microsoft Azure cloud services, enabling the latest versions of Apache Spark: an open-source engine providing large-scale APIs in general-purpose programming languages such as Scala, Python, and R. Specifically, Databricks provides a cloud-based interactive workspace with fully managed Spark clusters, allowing users to quickly execute Spark code in a easy-to-use environment.
```{r, eval=FALSE, echo=FALSE}
createOrReplaceTempView(df, "twitterTemp") # register table for SQL
```
------------------------------------
## Querying Twitter Data
When working with Twitter data, one of the first steps is distinguishing organic, user-written tweets from other tweet categories: retweets, replies, mentions, and quotes. By interpreting the tweet type ratio, we can glimpse into the general overview of a user's Twitter feed and account type.
```{r}
#x <- rtweet::network_data(gfg_data)
```
### Query 1. Tweet Types
<div class = "datasource2">
- What is the ratio of tweet types: mentions, replies, retweets, quotes, and organic tweets?
</div>
The different types of tweets that exist are **general tweets**, **mentions**, **replies**, **retweets**, and **quotes**. General tweets are original Twitter posts that include text, photos, GIFs, and videos but do not include mentions, replies, retweets, or quotes. Both mentions and replies are tweets containing other account usernames, though replies are specific tweets sent directly to another user's tweets. Lastly, retweets and quotes are re-postings of another person's tweets, although quotes allow users to post another tweet with their own added comment.
As a first step, we distinguish between organic tweets, retweets, and replies. With the data collected through the Twitter API, we can use specific columns such as `is_retweet` and `reply_to_status_id` to determine the tweet type. The following command removes retweets and replies from the data to keep only organic/generic tweets.
```{r, echo=TRUE, eval=FALSE}
# Remove retweets and replies
dfGeneral <- df[df$is_retweet == FALSE,] %>% subset(is.na(reply_to_status_id))
```
Similarly, we want to create a different dataset for each data type.
```{r, echo=TRUE, eval=FALSE}
dfMention <- subset(df, !is.na(df$mentions_user_id))
dfReply <- subset(df, !is.na(df$reply_to_status_id))
dfRtweet <- df[df$is_retweet == TRUE,]
dfQuote <- df[df$is_quote == TRUE,]
```
In the above, we subset the tweets into five datasets containing only general tweets, mentions, replies, retweets, or quotes. We then count the number of observations for each dataset using the `nrow()` function and store the information in a separate data frame containing the tweet types and their corresponding counts.
```{r, warning=FALSE, message=FALSE}
plotTypes <- lolli.types + labs(title = "Types of Tweets Count", subtitle = "Elon Musk's Tweets (2017-2022)") + theme(text = element_text(family = "Roboto Condensed"), plot.title = element_text(size = 14, colour = "gray5", face = "bold"), plot.subtitle = element_text(size = 12, colour = "gray20"))
ragg::agg_png(filename = "assets/static/tweetTypes.png", width = 7487, height = 4205, units = "px", res = 900)
plotTypes
invisible(dev.off())
knitr::include_graphics("assets/static/tweetTypes.png")
```
Now, for example, we can show information for each of Musk's retweets and query the data to obtain his most frequently retweeted users. To identify the most frequently retweeted users, we use tidyr tools to unnest, count, and sort each user from Musk's retweets.
```{r}
# dfRetweet %>% group_by(retweet_screen_name) %>% tally(sort = TRUE)
topRetweets <- plotRetweet +
plot_annotation(
title = "Top 12 Most Retweeted Users",
subtitle = "Elon Musk's Tweets (2017-2022)",
caption = "Source: twitter api dataset")
topRetweets <- topRetweets + plot_annotation(
theme = theme(text = element_text(family = "Roboto Condensed"),
plot.title = element_text(size = 13.25, colour = "gray5", face = "bold"),
plot.subtitle = element_text(size = 12, colour = "gray20"),
plot.caption = element_text(size = 8, face = "italic", colour = "gray40")))
# ragg::agg_png(filename = "assets/static/topRetweets.png", width = 8887, height = 5895, units = "px", res = 1050)
# topRetweets
# invisible(dev.off())
# knitr::include_graphics("assets/static/topRetweets.png")
```
-------------------------------
### Query 2. Mentions
<div class = "datasource2">
- How does Elon Musk engage with other twitter users?
</div>
To track Elon Musk's engagement with people on Twitter, we want to look into tweets containing conversations with and directed to other users. We begin by unpacking information for each of Musk's tweets that mention another person's username. Specifically, **mentions** are a type of tweet containing other account usernames, preceded by the "@" symbol.
```{r}
dfMentions_02 <- subset(gfg_data, !is.na(gfg_data$mentions_user_id)) %>% dplyr::select(created_at, mentions_user_id, mentions_screen_name, text)
tail(dfMentions_02, 50)[c(7, 29, 48),] %>%
kable(escape = FALSE) %>%
kable_styling(full_width = F, html_font = "Roboto Condensed", font_size = 10, bootstrap_options = c("hover", "striped")) %>%
add_header_above(c("Mentions" = 4), extra_css = c("font-weight: 400; letter-spacing: 0.25px; text-transform: uppercase; color: #1d9bf0; font-size: 9pt; text-shadow: 0.15px 0.15px 0.001px #12121240, -0.25px -0.25px 0.2px #d1d6e0f2, 0.25px 0.25px 0.25px #00000080, -0.2px -0.2px 0.1px #1a1a1a40, -0.5px -0.5px 0.2px #e6e6e680, 0.5px 0.5px 0.5px #b3b3b380; text-align: left;"))
```
As shown above, tweets can mention more than one user in the body of the text. Therefore, we have to process the data so that each user mentioned in the tweet is recorded in a separate row so that we can count the total number of times Musk mentioned a unique user.
```{r, echo=TRUE, eval=FALSE}
dfMentions %>% tibble(user = str_extract_all(text, "@\\w+")) %>%
tidyr::unnest_longer(user) %>% dplyr::count(user, sort = TRUE)
```
The above command uses the `str_extract_all()` function to extract the mentioned users for each tweet and `unnest_longer()` to transform the nested lists into tidy rows so that each row contains only one user. Lastly, we count the total number of observations for each unique user.
```{r}
dfMentions <- dfMentions %>% head(10)
timeMent <- c()
for (user in dfMentions$screen_name) {
data <- dplyr::filter(
gfg_data, grepl(tolower(user), tolower(mentions_screen_name))) %>%
dplyr::select(created_at)
timeMent <- c(timeMent, c(data))
}
dfMentions <- dfMentions %>%
dplyr::mutate(mention_time = (timeMent),
mention_time2 = (timeMent))
dfMentions %>%
gt::gt() %>%
gtExtras::gt_color_rows(columns = n, palette = "ggsci::blue_material") %>%
gtExtras::gt_plt_dist(column = mention_time, type = "density", line_color = "black", fill_color = "gray80", fig_dim = c(5,32)) %>%
gtExtras::gt_plt_dist(column = mention_time2, type = "rug_strip", line_color = "black", fill_color = "blue", fig_dim = c(5,30)) %>%
gtExtras::gt_theme_espn()
```
```{r, fig.show='hold'}
topMentions <- plot.Mentions + table.Mentions + plot_annotation(
title = "Top 12 Most Mentioned Users",
subtitle = "Elon Musk's Tweets (2017-2022)",
caption = "Source: twitter api dataset")
topMentions <- topMentions + plot_annotation(
theme = theme(text = element_text(family = "Roboto Condensed"),
plot.title = element_text(size = 13.25, colour = "gray5", face = "bold"),
plot.subtitle = element_text(size = 12, colour = "gray20"),
plot.caption = element_text(size = 8, face = "italic", colour = "gray40"))) +
plot_layout(widths = c(2, 1))
# ragg::agg_png(filename = "assets/static/userMentions.png", width = 8887, height = 5495, units = "px", res = 1000)
# topMentions
# invisible(dev.off())
# knitr::include_graphics("assets/static/userMentions.png")
```
Linking conversations together, a **reply** is a type of tweet sent directly to another user's tweet. Analogous to mentions, replies allow users to direct tweets toward other Twitter users and interact in conversations. Continuing the same general procedure above, we get the following results.
```{r}
topReply <- (plotReplies + ggtitle("Top 12 Most Replied To Users") +
theme(plot.title = element_text(size = 13, margin = ggplot2::margin(b=-1)))) +
(plot.Mentions2 + ggtitle("Top 12 Most Mentioned Users") +
theme(plot.title = element_text(size = 13, margin = ggplot2::margin(b=-1))))
topReply <- topReply + plot_annotation(
theme = theme(text = element_text(family = "Roboto Condensed"),
plot.title = element_text(size = 13.25, colour = "gray5", face = "bold"),
plot.subtitle = element_text(size = 12, colour = "gray20")))
ragg::agg_png(filename = "assets/static/topReplies.png", width = 9487, height = 4695, units = "px", res = 1050)
topReply
invisible(dev.off())
knitr::include_graphics("assets/static/topReplies.png")
```
-------------------------------
### Query 3. Twitter Activity
<div class = "datasource2">
- Are there any trends of when Elon Musk tweets?
</div>
Here, we provide an overview of Musk's Twitter activity by analyzing the frequency of tweets by timeframes such as year, month, weekday, hour, and time of day. Parsing the information from the `created_at` column, we extract timestamps to display the year, month, day, and hour of each tweet's posting date.
```{r, echo=TRUE, eval=FALSE}
df$created_at <- to_timestamp(df$created_at)
df$year <- year(df$created_at)
df$month <- date_format(to_date(df$created_at), "MMMM")
df$weekday <- date_format(to_date(df$created_at), "EEEE")
```
```{r}
dfTime %>% dplyr::select(-status_id) %>% slice_sample(n = 10) %>%
dplyr::arrange(desc(created_at)) %>% head() %>%
kable(escape = F) %>%
kable_styling(full_width = F, html_font = "Roboto Condensed", font_size = 12, bootstrap_options = c("striped", "hover")) %>%
column_spec(1, extra_css = c("opacity: 0.5;"))
```
The above data allows us to explore Musk's Twitter usage, ranging from the frequency of tweets over years to which days of the week or hours of the day have more or less activity. As a result, we see that Musk is most active on Thursdays and Fridays, mostly tweeting at night.
```{r, message=FALSE, warning=FALSE}
plotYear <- ggplot(dfTime) + geom_bar(mapping = aes(x = year), stat = "count", fill="#A0F5F7", alpha=0.85, color="black") + xlab("year") + ylab(NULL) + theme_ipsum_rc(base_size = 10, plot_margin = ggplot2::margin(10,10,10,10), axis_title_face = "bold", axis_title_size = 10) + theme(axis.title.x = element_text(vjust = 0.25))
plotMonth <- ggplot(dfTime) + geom_bar(mapping = aes(x = factor(month, levels = month.name, labels = month.abb)), stat = "count", fill = "#2DDAF4", alpha=0.85, color="black") + xlab("month") + ylab(NULL) + theme_ipsum_rc(base_size = 10, plot_margin = ggplot2::margin(10,10,10,10), axis_title_face = "bold", axis_title_size = 10) + theme(axis.title.x = element_text(vjust = 0.25))
plotDay <- ggplot(dfTime) + geom_bar(mapping = aes(x = factor(weekday, levels= c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"), labels =c("Sun", "Mon", "Tues", "Weds", "Thurs", "Fri", "Sat"))), stat = "count", fill = "#3C84F0", alpha=0.85, color="black") + xlab("weekday") + ylab(NULL) + theme_ipsum_rc(base_size = 10, plot_margin = ggplot2::margin(10,10,10,10), axis_title_face = "bold", axis_title_size = 10) + theme(axis.title.x = element_text(vjust = 0.25))
plotTime <- ggplot(dfTime) + geom_bar(mapping = aes(x = time), stat = "count", fill = "#00326F", alpha=0.85, color="black") + xlab("time") + ylab(NULL) + theme_ipsum_rc(base_size = 10, plot_margin = ggplot2::margin(10,10,10,10), axis_title_face = "bold", axis_title_size = 10) + theme(axis.title.x = element_text(vjust = 0.25))
```
```{r, message=FALSE, warning=FALSE}
plotDateTime <- ggarrange(plotYear, plotMonth, plotDay, plotTime, ncol = 2, nrow = 2)
plotDateTime <- annotate_figure(plotDateTime, top = text_grob("Number of Tweets by Datetime", family = "Roboto Condensed", size = 12, hjust = 1.75, vjust = 0.12, face = "bold"))
ragg::agg_png(filename = "assets/static/reportDate.png", width = 8287, height = 6095, units = "px", res = 1100)
plotDateTime
invisible(dev.off())
knitr::include_graphics("assets/static/reportDate.png")
```
We can go even deeper and look at the exact time and day of the week in which Musk has the most activity posting tweets with a detailed histogram. Consistent with our previous results, we see the most activity on Thursdays at 6 pm.
```{r}
colpal3 <- c("#E1B1FB","#9F00F5", "#340069","#0B0042", "#12167D", "#1e40eb","#2b80f2", "#35AEF6", "#3fdbf9","#82FAF5","#C4FEFA", "#EBFFFD")
```
```{r, fig.show='hold'}
# TWEETS PER DAY AND HOUR
x <- dfTime %>% mutate(hr = hms::hms(hours= hour(created_at), minutes = minute(created_at))) %>%
ggplot(mapping = aes(x = weekday, y = hr)) +
geom_bin2d(bins = 24, cex = 0.185, color = "#e0e2e680") +
scale_fill_gradientn(colours = rev(colpal3), values = c(0,1.25)) + theme_ipsum_rc(base_size = 10) + ggtitle("Tweets per day of the week and hour") + xlab("weekday") + ylab("hour") + theme(legend.title = element_blank(), plot.title = element_text(size = 10), panel.grid.minor.y = element_blank(), axis.text.y = element_text(size = 8, colour = "#3c4043"), axis.text.x = element_text(size = 8.5, colour = "#3c4043"), legend.text = element_text(size = 7, colour = "#3c4044bf"))
ggplotly(x)
```
-------------------------------
### Query 4. Tweet Topics
<div class = "datasource2">
- What are Elon Musk’s most tweeted topics?
</div>
Continuing to analyze Musk's habits on Twitter, we want to know which topics dominate Musk's Twitter feed. To get such topics and themes of the user content, we examine the most frequently used hashtags and words for all of Musk's tweets. Extracting unique hashtags and words from a tweet requires text mining tasks.
<span class="myhighlight2">Hashtags:</span>
We first extract hashtags, all words preceded with a `#` character, from the content of Musk's tweets. The following command cleanses and unpacks the text of each tweet to get a string array containing only the hashtags. Then, we calculate the frequency of each unique hashtag.
```{r, echo=TRUE, eval=FALSE}
hashtag <- df$text %>% str_extract_all("#[A-Za-z0-9_]+")
hashtag_word <- unlist(hashtag)
hashtag_word <- tolower(hashtag_word)
hashtag_word <- gsub("[[:punct:]ー]", "", hashtag_word)
```
```{r}
hashtag <- gfg_data$text %>% str_extract_all("#[A-Za-z0-9_]+")
hashtag_word <- unlist(hashtag)
hashtag_word <- tolower(hashtag_word)
hashtag_word <- gsub("[[:punct:]ー]", "", hashtag_word)
# as.data.frame(hashtag_word) %>%
# dplyr::count(hashtag_word, sort = TRUE) %>%
# top_n(20) %>%
# ggplot(aes(x = reorder(hashtag_word, n), y = n)) +
# geom_col() +
# coord_flip()
```
```{r, fig.show='hold'}
topHashtag <- ggarrange(plotTags, tableTags, widths = c(2, 1), heights = c(1, 1), labels = c("Top 12 Most Used Hashtags"), font.label = list(size = 10, family = "Roboto"))
ragg::agg_png(filename = "assets/static/topHashtag.png", width = 7087, height = 4595, units = "px", res = 900)
topHashtag
invisible(dev.off())
knitr::include_graphics("assets/static/topHashtag.png")
```
<span class="myhighlight2">Topic Words:</span>
Next, let's look at the words Musk mentioned the most in his tweets. We first clean up the text in the data by removing punctuation, URL links, and symbols, and use tools to convert the text into a tidy format. Then, we split the text into individual words and remove stop words.
```{r, echo=TRUE, eval=FALSE}
# Regex for parsing tweets
replace_reg <- "https?://[^\\s]+|&|<|>|\bRT\\b|^<"
# Clean text
words <- dfGeneral %>%
dplyr::mutate(
text = str_remove_all(text, replace_reg),
text = str_remove_all(text, "[[:punct:]]"),
text = str_remove_all(text, "[[:digit:]]")) %>%
# Split into words
unnest_tokens(word, text, token = "tweets") %>%
# Remove stop words
anti_join(stop_words, by = "word")
```
In the above command, the pattern matching function `str_remove_all()` removes unwanted text, and the `unnest_tokens()` function splits the text of each tweet into tokens, using a one-word-per-row format. We then use the `str_detect()` function to filter out words by removing stop words, unicode characters, and whitespace.
```{r}
top40Words <- ggarrange(plot.lolli, plot.circle, ncol = 2, widths = c(3, 4), heights = c(1, 1))
ragg::agg_png(filename = "assets/static/top40Words.png", width = 9087, height = 5295, units = "px", res = 1600)
plot.lolli2
invisible(dev.off())
knitr::include_graphics("assets/static/top40Words.png")
```
```{r}
top15Words <- ggarrange(plotWords, plot.circle, ncol = 2, widths = c(3, 4), heights = c(1, 1), labels = c("Top 15 Most Used Words"), font.label = list(size = 10, family = "Roboto"))
ragg::agg_png(filename = "assets/static/top15Words.png", width = 9087, height = 4195, units = "px", res = 1100)
top15Words
invisible(dev.off())
knitr::include_graphics("assets/static/top15Words.png")
```
Above, we used the `unnest_tokens` function to tokenize by word; however, we can also use these functions to tokenize into consecutive sequences of words, called n-grams. We do this by adding the option `token = "ngrams"` and setting $n$ to the number of words. Setting n to $2$ allows us to examine pairs of two consecutive words, often called *bigrams*.
```{r}
organic_tweets <- gfg_data[gfg_data$is_retweet == FALSE,] %>% subset(is.na(reply_to_status_id))
dfGeneral <- organic_tweets
# Regex for parsing tweets
replace_reg <- "https?://[^\\s]+|&|<|>|\bRT\\b|^<"
colpal3 <- c("#E1B1FB","#9F00F5", "#340069","#0B0042", "#12167D", "#1e40eb","#2b80f2", "#35AEF6", "#3fdbf9","#82FAF5","#C4FEFA", "#EBFFFD")
```
```{r, echo=TRUE, eval=TRUE}
bigrams <- dfGeneral %>%
dplyr::mutate(text = str_replace_all(text, replace_reg, "")) %>%
# split into word pairs
unnest_tokens(bigram, text, token = "ngrams", n = 2) %>%
separate(bigram, into = c("first","second"), sep = " ", remove = FALSE) %>%
# remove stop words
anti_join(stop_words, by = c("first" = "word")) %>%
anti_join(stop_words, by = c("second" = "word")) %>%
filter(str_detect(first, "[a-z]") & str_detect(second, "[a-z]"))
```
```{r}
bigram_data <- bigrams %>%
group_by(bigram) %>%
dplyr::count()
bigram_tbl <- tibble(
name = bigram_data$bigram,
freq = bigram_data$n) %>%
arrange(desc(freq)) %>%
head(10)
timeBgrm <- c()
for (biword in bigram_tbl$name) {
data <- dplyr::filter(dfGeneral, grepl(biword, tolower(text))) %>%
dplyr::select(created_at)
timeBgrm <- c(timeBgrm, c(data))
}
bigram_tbl <- bigram_tbl %>%
dplyr::mutate(time_posted = (timeBgrm))
bigram_tbl %>%
gt::gt() %>%
gtExtras::gt_theme_espn() %>%
gt::data_color(
columns = freq,
colors = scales::col_numeric(
palette = colpal3,
domain = c(10, 35)
)
) %>%
gtExtras::gt_plt_dist(column = time_posted, type = "density", line_color = "black", fill_color = "gray80", fig_dim = c(5,32),trim = FALSE,same_limit = TRUE)
```
------------------------------------
## Sentiment Analysis
Here we use the `syuzhet` R package to iterate over a vector of strings consisting of the text from all of Elon Musk's tweets in our dataset. To obtain the vector of tweet text, the plain_tweets() function from the `rtweet` package is used to clean up the tweets character vector to cleaned up, plain text. We then pass this vector to the get_sentiment() function, which consequently returns the sentiment values based on the custom sentiment dictionary developed from a collection of human coded sentences.
```{r,echo=TRUE}
round_time <- function(x, secs)
as.POSIXct(hms::round_hms(x, secs))
sent_scores <- function(x)
syuzhet::get_sentiment(plain_tweets(x)) - .5
df.sentiment <- gfg_data %>%
dplyr::mutate(days = round_time(created_at, 60 * 60 * 24),
sentiment = sent_scores(text)) %>%
dplyr::group_by(days) %>%
dplyr::summarise(sentiment = sum(sentiment, na.rm = TRUE))
```
```{r, warning=FALSE, message=FALSE, out.width="100%"}
ggplotly(tt_sent)
```
Extending the above sentiment analysis, the next step is to understand the opinion or emotion in the text. First, we must clean the text from our dataset so that it's in a tidy format. We accomplish this using the R function `gsub()` to replace unwanted text and the `get_nrc_sentiment()` function to get the emotions and valences from the NRC sentiment dictionary for each word from all of Musk's tweet.
<span class="myhighlight2">R Code: </span>
```{r, eval=FALSE, echo=TRUE}
txt <- c("rt|RT", "http\\w+", "<.*?>", "@\\w+", "[[:punct:]]", "\r?\n|\r", "[[:digit:]]", "[ |\t]{2,}", "^ ", " $")
cleanTweet <- as.vector(df$text)
cleanTweet <- grep::gsub(txt, "", cleanTweet)
textSentiment <- syuzhet::get_nrc_sentiment(cleanTweet)
nrc_sentiment <- cbind(df, textSentiment) %>%
dplyr::select(created_at, anger, anticipation, disgust, fear,
joy, sadness, surprise, trust, negative, positive)
```
In the above command, the gsub function replaces all occurrences of the given patterns and the get_nrc_sentiment function calculates the presence of eight different emotions and their corresponding valence. The resulting columns include the eight emotions `disgust`, `fear`, `joy`, `sadness`, `surprise`, `trust` and their respective `positive` or `negative` valence.
```{r, out.width="100%"}
ggsenti1 <- ggarrange(ggarrange(plot.sent1, plot.sent1B, widths = c(5, 4)),
plot.ridges1, nrow = 2, ncol = 1, heights = c(6, 6))
ragg::agg_png(filename = "assets/static/senti1.png", width = 8087, height = 6895, units = "px", res = 1100)
ggsenti1
invisible(dev.off())
knitr::include_graphics("assets/static/senti1.png")
```
```{r, out.width="100%"}
#ggsenti2 <- ggarrange(plot.sent2, plot.sent3, ncol = 2, nrow = 1, align = "hv", widths = c(4, 3))
ragg::agg_png(filename = "assets/static/senti2.png", width = 8887, height = 6895, units = "px", res = 1100)
plot.sent2
invisible(dev.off())
knitr::include_graphics("assets/static/senti2.png")
```
```{r}
# ragg::agg_png(filename = "assets/static/senti3.png", width = 8887, height = 6095, units = "px", res = 900)
# plot.sent2A
# invisible(dev.off())
# knitr::include_graphics("assets/static/senti3.png")
radarplot <- (myradarChart(radarDF2, colors_border, colors_in, mytitle))
# plot.sent2A
# plot.sent2B
# plotRadar
```
------------------------------------
## Conclusion
This project showed how to extract and analyze twitter data using various essential packages in R. The above Twitter analytics report for Elon Musk's tweets covered insights regarding Musk's tweeting behavior, insights on the content of Musk's tweets, and a sentiment analysis capturing the tone of the tweets.
The first question examines Musk's tweet distribution, which we answer by sorting each tweet into categories (based on tweet types) and ranking each category based on the volume of tweets. Analyzing Musk's nature of engagement, we answer the second question by unpacking tweets containing conversations with and directed to other users. To answer the third question, we investigate Musk's Twitter activity by sorting his feed into different timeframes based on the publish date. Dissecting the topics that predominate his profile feed, we answer the fourth question by examining Musk's most frequently used hashtags and words.
\
### References