-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClass_Project_Report.Rmd
More file actions
683 lines (560 loc) · 33.7 KB
/
Class_Project_Report.Rmd
File metadata and controls
683 lines (560 loc) · 33.7 KB
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
---
title: "Analyzing the Sentiment Towards Ridesharing Services and Public Transportation in Washington D.C."
author: "Mohammad Al-khasawneh"
date: "`r Sys.Date()`"
subtitle: "GitHub: https://github.com/mbmk2020/FOCD2021_Final_Project"
fontsize: 12pt
mainfont: Calibri
output:
pdf_document:
toc: yes
fig_caption: yes
keep_tex: yes
html_document:
fig_caption: yes
number_sections: yes
toc: yes
toc_float: yes
df_print: kable
theme: simplex
word_document:
toc: yes
params:
year: 2021
data: !r mtcars
link-citations: yes
linkcolor: blue
bibliography: references.bib
---
\newpage
```{r setup, eval=FALSE, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Introduction
The growth of the population and their mobility needs require other alternative transportation systems such as ride-sharing services. The ride-sharing services are more promising for people's needs in terms of cost and time since they are app-based use smartphone technology in their functionality. They can be considered a potential solution to meet the needs of passengers in terms of flexibility and cost without expanding the service frequency of public transportation. Both of these ride services are highly demanding in the metropolitan where people tend to avoid driving or having their cars to avoid delays or parking difficulties accompanied by the dense population in the area. The first impression about these ride services is that Public transportation is usually cheaper than ride-sharing services. On the other hand, ride-sharing services may be faster and easier to access. The main objective of this research project is to answer these questions through a sentiment analysis for people’s Twitter posts to extract their feelings about the available alternatives of public transportation and ride-sharing services. The Washington D.C. metropolitan area is selected as the geographical area for this study. Three services included Uber, Lyft, and the normal Taxi are selected to study people's opinions about ride-sharing services, whereas the Amtrak, Metro, and Metrobus were selected to study people's opinions about the public transportation services. Social media has become more popular and is widely used by people of all ages. Twitter is one of the most popular social media with millions of active users monthly. Many organizations, business companies specifically, use this social media to gain some feedback for their business.
# Motivation
The motivation for doing this research project is to answer the questions of what people prefer to use: public transportation or ridesharing services through a sentiment analysis using Twitter posts. Both Twitter data and sentiment analysis are motivated keys for the project. Several research studies have been done in the field of transportation engineering using sentiment analysis. Sonia et al. [-@Sonia16] have used Twitter data to measure and compare customer satisfaction between two companies that provide online transportation services. They used the sentiment analysis technique and found that most of the Twitter posts were for bad experiences with these two companies. Another study by Eddendy et al. [-@Effendy16] conducted sentiment analysis for Twitter posts about the use of public transportation in the big cities in Indonesia. These research studies have provided good examples of how Twitter data and sentiment analysis can be used in the field of transportation engineering. Therefore, I was motivated to do a comprehensive comparison to include both the public transportation and the ridesharing services in one comparison. Another reason that motivates me to choose twitter data is that people get the chance to speak more honestly there about their opinions.
# Installing Scripts
## Required packages
The following are the packages used in this research project. The "twitterR" package was used for search twitter data with specific geographical location and search terms. The "tidytext" and "dplyer" packages were used for data manipulation. Finally, the packages of "ggmap" and "gridExtra" were used for data visualization and plot organizations.
```{r, echo=TRUE, eval=FALSE}
install.packages(c("mnormt", "psych", "SnowballC",
"hunspell","broom", "tokenizers", "janeaustenr"))
install.packages("twitteR")
install.packages("tidytext")
install.packages("ggmap")
install.packages("tcltk")
install.packages("gridExtra")
install.packages("dplyr")
install.packages("kableExtra")
install.packages("sentimentr")
```
## Required libraries
The following are the specific libraries used in this project.
```{r, echo=TRUE,message=FALSE}
library(twitteR)
library(tidyverse)
library(tidytext)
library(ggmap)
library(tcltk)
library(gridExtra)
library(scales)
library(dplyr)
library(kableExtra)
library(sentimentr)
```
## Setup the twitter API
In order to be able to use the twitter API the following are the keys and tokens requested through twitter developer website https://developer.twitter.com/en in order to be able to use the twitter API.
```{r, echo=TRUE, message=FALSE, results='hide'}
# The keys were hidden for privacy.
consumer_key <- "consumer_key_XX"
consumer_secret <- "consumer_secret_XX"
access_token <- "access_token_XX"
access_secret <- "access_secret_XX"
# This step is needed to setup the twitter API and before we start
# searching for data. It made as comment because the keys have to be real
# and active in order to run this line without errors. If you set your keys
# you can remove the "#" and run this line:
# setup_twitter_oauth(consumer_key, consumer_secret, access_token,
# access_secret)
```
# Data
The first part of the project is data gathering. The data used in this study was mainly from twitter posts. The data obtained from twitter API using 'twitterR' package. The API provides the user with an access token that gives the user access to searching for tweets and information about them and stores them in a data frame. The data includes people twitter posts about the available public transportation: Amtrak, Metro, and Metrobus services and also the ridesharing services including: Uber, Lyft, and the normal cab Taxi. The obtained data covered mainly the area of Washington D.C. and up to Baltimore area as many of these ride services lives in Baltimore as well. Since The twitter API gives only access to the most recent 8 days, the data for this project was combined for four separate searches conducted on following dates: Nov 2nd, Nov 12, Nov 22, and Dec 2nd.
## Searching data using twitter API
The following is the code used to search for Twitter posts about each ride service:
```{r, include=TRUE, message=FALSE}
##Ridesharing services
#Taxi <- twListToDF(searchTwitter("taxi", geocode = "38.907,-77.036,60mi",
# n = 5000,lang="en"))
#Uber <- twListToDF(searchTwitter("Uber", geocode = "38.907,-77.036,60mi",
# n = 5000,lang="en"))
#Lyft <- twListToDF(searchTwitter("Lyft", geocode = "38.907,-77.036,60mi",
# n = 5000,lang="en"))
#Ridesharing_Services <- rbind(Taxi, Uber, Lyft)
##Public transportation
#Amtrak <- twListToDF(searchTwitter("amtrak", geocode = "38.907,-77.036,
# 60mi",n = 5000,lang="en"))
#metrobus <- twListToDF(searchTwitter("metrobus", geocode = "38.907,-77.036,
# 60mi",n = 5000,lang="en"))
#metro <- twListToDF(searchTwitter("metro", geocode = "38.907,-77.036,
# 60mi",n = 5000,lang="en"))
#Public_Transportation <- rbind(Amtrak, metro, metrobus)
```
```{r,include=FALSE}
# This code is to save the collected data to the a local storage place:
# Date_of_Search <- "_12.02.2021"
# directory_to_save <-
# "Data/"
#
# write.csv(apply(Taxi,2,as.character),paste0(directory_to_save,
# "Taxi",Date_of_Search,".csv"))
# write.csv(apply(Uber,2,as.character),paste0(directory_to_save,
# "Uber",Date_of_Search,".csv"))
# write.csv(apply(Lyft,2,as.character),paste0(directory_to_save,
# "Lyft",Date_of_Search,".csv"))
# write.csv(apply(Ridesharing_Services,2,as.character),
# paste0(directory_to_save,"Ridesharing_Services",
# Date_of_Search,".csv"))
#
# write.csv(apply(Amtrak,2,as.character),paste0(directory_to_save,
# "Amtrak",Date_of_Search,".csv"))
# write.csv(apply(metro,2,as.character),paste0(directory_to_save,
# "metro",Date_of_Search,".csv"))
# write.csv(apply(metrobus,2,as.character),paste0(directory_to_save,
# "metrobus",Date_of_Search,
# ".csv"))
# write.csv(apply(Public_Transportation,2,as.character),
# paste0(directory_to_save,"Public_Transportation",Date_of_Search,
# ".csv"))
```
## Combining data for one month history
The downloaded searches were stored at the local storage and then were combined into one dataframe for each ride service.
```{r,include=FALSE,message=FALSE}
# Here are all the search dates to combine them in one file for each service
Date_of_Search <- c("_11.02.2021","_11.12.2021","_11.22.2021","_12.02.2021")
# Here is the directory I use to save the data and then to pull the data from (it can be changed to the directory where you have the data files in):
directory_to_save <-
"Data/"
#Ridesharing services
Taxi.tweets <- data.frame()
Uber.tweets <- data.frame()
Lyft.tweets <- data.frame()
RSS.tweets <- data.frame() #RSS = Ride sharing services
for (i in Date_of_Search){
Uber.tweets <-
read.csv(paste0(directory_to_save,"Uber",i,".csv")) %>%
select(text) %>%mutate(Service = "Uber", date = i) %>%
rbind(Uber.tweets)
Lyft.tweets <-
read.csv(paste0(directory_to_save,"Lyft",i,".csv")) %>%
select(text) %>%mutate(Service = "Lyft", date = i) %>%
rbind(Lyft.tweets)
Taxi.tweets <-
read.csv(paste0(directory_to_save,"Taxi",i,".csv")) %>%
select(text) %>% mutate(Service = "Taxi", date = i) %>%
rbind(Taxi.tweets)
}
RSS.tweets <- rbind(Uber.tweets, Lyft.tweets,Taxi.tweets)
#Public transportation
Amtrak.tweets <- data.frame()
metro.tweets <- data.frame()
metrobus.tweets <- data.frame()
PT.tweets <- data.frame() #PT = Public Transportation
for (i in Date_of_Search){
Amtrak.tweets <-
read.csv(paste0(directory_to_save,"Amtrak",i,".csv")) %>%
select(text) %>%mutate(Service = "Amtrak", date = i) %>%
rbind(Amtrak.tweets)
metro.tweets <-
read.csv(paste0(directory_to_save,"metro",i,".csv")) %>%
select(text) %>%mutate(Service = "metro", date = i) %>%
rbind(metro.tweets)
metrobus.tweets <-
read.csv(paste0(directory_to_save,"metrobus",i,".csv")) %>%
select(text) %>% mutate(Service = "metrobus", date = i) %>%
rbind(metrobus.tweets)
}
PT.tweets <- rbind(Amtrak.tweets, metro.tweets,metrobus.tweets)
```
The following table summaries the number of twitter posts obtained for each ride service:
```{r,include=FALSE,message=FALSE}
summary_table <- data.frame()
count_searches <- function (data_tweets){
return(c(length(data_tweets[data_tweets$date=="_11.02.2021",]$text),
length(data_tweets[data_tweets$date=="_11.12.2021",]$text),
length(data_tweets[data_tweets$date=="_11.22.2021",]$text),
length(data_tweets[data_tweets$date=="_12.02.2021",]$text)) )
}
Uber_searches <- count_searches(Uber.tweets)
Lyft_searches <- count_searches(Lyft.tweets)
Taxi_searches <- count_searches(Taxi.tweets)
Amtrak_searches <- count_searches(Amtrak.tweets)
Metro_searches <- count_searches(metro.tweets)
Metrobus_searches <- count_searches(metrobus.tweets)
summary_table <- as.data.frame(rbind(Uber_searches,Lyft_searches,Taxi_searches,
Amtrak_searches,Metro_searches,Metrobus_searches)) %>%
mutate(Total = rowSums(.))
rownames(summary_table) <- c("Uber","Lyft","Taxi","Amtrak","Metro","Metrobus")
colnames(summary_table) <- c("11.02.2021","11.12.2021","11.22.2021","12.02.2021","Total")
```
```{r, echo=FALSE, message=FALSE}
summary_table %>%
kbl(position = "center")
```
# Data Analysis
After the required data was gathered and stored in data frames. The data was cleaned out from the uninformative words through some tokenization steps. Different functions were created to remove “stop” words such as “and”, “the”, “of”, “or” as well as twitter specific words such as “rt” etc. The function also splits the tweets into individual words and removes all hashtags and signs.
After tokenizing and cleaning the data, the tweets were fed to specific functions of each package. For the first packages "tidytext", the function takes the tweets and returns a score for each tweet. This score is then classified according to a function coded into positive and negative and their the score which represent the repetitive of each word.
Finally, a data table is created from the positive and negative classification and a graph is created to visualize the results. The following section will have more detailed description for each step in the data analysis.
## Data Pre-proccessing and Tokanization
The following code is for data cleaning and tokenizing:
```{r,message=FALSE}
Tokenization_fun <- function(df){
df$text = gsub("(f|ht)(tp)(s?)(://)(.*)[.|/](.*)", " ", df$text)
#removing link
df$text = gsub("(f|ht)(tp)(s?)(://)(.*)[.|/](.*)", " ", df$text)
# removing hashtags
df$text = gsub("#\\w+", " ", df$text)
# removing @people
df$text = gsub("@\\w+", " ", df$text)
#removing punctuations
df$text = gsub("[[:punct:]]", " ", df$text)
#removing numbers
df$text = gsub("[[:digit:]]", " ", df$text)
#removing emojis
df$text <- str_replace_all(df$text,"[^[:graph:]]"," ")
df$text <- str_replace_all(df$text,'https'," ")
df$text <- str_replace_all(df$text,'amp'," ")
#removing spaces
df$text = gsub("[ \t]{2,}", " ", df$text)
df$text = gsub("^\\s+|\\s+$", "", df$text)
return(df)
}
Taxi.tweets <- Tokenization_fun(Taxi.tweets)
Uber.tweets <- Tokenization_fun(Uber.tweets)
Lyft.tweets <- Tokenization_fun(Lyft.tweets)
RSS.tweets <- rbind(Taxi.tweets, Uber.tweets, Lyft.tweets)
Amtrak.tweets <- Tokenization_fun(Amtrak.tweets)
metro.tweets <- Tokenization_fun(metro.tweets)
metrobus.tweets <- Tokenization_fun(metrobus.tweets)
PT.tweets <- rbind(Amtrak.tweets, metro.tweets, metrobus.tweets)
```
After data cleaning and tokenizing. The tweets were passed into unnset_tokens() function in order to split them into individual words using:
```{r,message=FALSE}
#Ride Sharing Services
Taxi.tweets_stem <-
Taxi.tweets %>% select(text)%>%unnest_tokens(word, text) %>%
anti_join(stop_words)
Uber.tweets_stem <-
Uber.tweets %>% select(text)%>%unnest_tokens(word, text) %>%
anti_join(stop_words)
Lyft.tweets_stem <-
Lyft.tweets %>% select(text)%>%unnest_tokens(word, text) %>%
anti_join(stop_words)
RSS.tweets_stem <- rbind(Taxi.tweets_stem,Uber.tweets_stem,Lyft.tweets_stem)
#Public Transportation
Amtrak.tweets_stem <-
Amtrak.tweets %>% select(text)%>%unnest_tokens(word, text) %>%
anti_join(stop_words)
metro.tweets_stem <-
metro.tweets %>% select(text)%>%unnest_tokens(word, text) %>%
anti_join(stop_words)
metrobus.tweets_stem <-
metrobus.tweets %>% select(text)%>%unnest_tokens(word, text) %>%
anti_join(stop_words)
PT.tweets_stem <- rbind(Amtrak.tweets_stem, metro.tweets_stem,
metrobus.tweets_stem)
```
In order to check whether the collected searches have included some relevant words to transportation or not, the most common words in people's twitter posts about ridesharing services and public transportation were counted and ploted as shown in Figure 1.
```{r, echo=FALSE, message=FALSE}
plot1<-
RSS.tweets_stem %>%
count(word, sort = TRUE) %>%
top_n(10) %>%
mutate(word = reorder(word,n)) %>%
ggplot(aes(x=word, y=n))+
ylab("Frequency")+
ggtitle("Ridesharing services")+
geom_col()+
coord_flip()+
theme_light()+
theme(plot.title = element_text(hjust = 0.5))
plot2<-
PT.tweets_stem %>%
count(word, sort = TRUE) %>%
top_n(10) %>%
mutate(word = reorder(word,n)) %>%
ggplot(aes(x=word, y=n))+
ylab("Frequency")+
ggtitle("Public transportation services")+
geom_col()+
coord_flip()+
theme_light()+
theme(plot.title = element_text(hjust = 0.5))
grid.arrange(plot1, plot2, ncol=2,
bottom ="Figure 1. Most common words")
```
## Sentiment lexicons using "tidytext"
There are several ways for evaluating the opinion or emotion in text. The sentiment lexicons provides analysis at the word level by splitting the whole sentence into individual words and then assigns words into different categories or feelings with specific scores. The sentiment lexicons can be done using tidytext package in R. There are also several lexicons such as: bing from (Bing Liu and collaborators, 2004), ncr by (Saif Mohammad and Peter Turney, 2010) , and AFINN from ( Finn Årup Nielsen, 2011). The bing sentiment analysis will be used for this research project for doing the analysis at the word level.
Bing Sentiment Analysis
The bing lexicon categorizes words into positive and negative feelings. The get_sentiment("bing") from [-@tidytext] the function was used to obtain the sentiment dictionary for the list of words prepared by (Bing Liu and collaborators, 2004). Then the inner_hoin() was used to match each word in our data set with the appropriate feelings and sentiment score (-1 or 1). The function sentiment_score_bing() was prepared for this project to to calculate the sentiment score and feeling for each word by by passing the list of cleaned words from twitter posts. Finally each word in our dataset about each ride service will were assigned to "Positive" or "Negative" feelings according to the bing dictionary. This was done using following code:
```{r,message=FALSE}
sentiment_score_bing <- function(tweets_stem){
tweets_stem %>%
inner_join(get_sentiments("bing")) %>%
mutate(value = case_when(
sentiment=="negative"~-1,
sentiment=="positive"~1
))%>%
count(word, sentiment,value, sort = TRUE) %>%
ungroup()
}
Uber.tweets_Sentiment <- sentiment_score_bing(Uber.tweets_stem)
Lyft.tweets_Sentiment <- sentiment_score_bing(Lyft.tweets_stem)
Taxi.tweets_Sentiment <- sentiment_score_bing(Taxi.tweets_stem)
RSS.tweets_Sentiment <- sentiment_score_bing(RSS.tweets_stem)
Amtrak.tweets_Sentiment <- sentiment_score_bing(Amtrak.tweets_stem)
metro.tweets_Sentiment <- sentiment_score_bing(metro.tweets_stem)
metrobus.tweets_Sentiment <- sentiment_score_bing(metrobus.tweets_stem)
PT.tweets_Sentiment <- sentiment_score_bing(PT.tweets_stem)
```
The following Figure 2 and Figure 3 show the most common positive and negative words in the collected twitter posts about the ridesharing services and the public transportation, respectively.
```{r,message=FALSE, echo=FALSE}
# Create a function to plot the top 10 negative and positive words for people
# tweets about the ride services in Washington D.C. area
plot_sentiment <- function(tweets_sentiment, top_words=10, figure_title){
tweets_sentiment %>%
group_by(sentiment) %>%
top_n(top_words) %>%
ungroup() %>%
mutate(Percentage = n/sum(n)) %>%
mutate(word = reorder(word,Percentage)) %>%
ggplot(aes(word, Percentage, fill=sentiment))+
geom_col(show.legend = F)+
geom_text(aes(label = label_percent()(Percentage) ), nudge_y = 0.025,
size = 3)+
facet_wrap(~sentiment, scales = "free_y")+
coord_flip()+
theme_bw()+
labs(caption = figure_title)+
theme(plot.caption = element_text(hjust = 0.5, size = 12))
}
plot_sentiment(RSS.tweets_Sentiment, 10,
"Figure 2. Common negative and Poitive words for the Ridesharing services")
plot_sentiment(PT.tweets_Sentiment, 10,
"Figure 3. Common negative and Poitive words for the Public Transporatio")
```
The next step is to count up the positive and negative words for each ride service. Then the percentage of each category was calculated out of the total number of words. The following code shows the total_sentiment_score() function used to calculate the percentages of the positive and negative opinions about the ride service in the collected twitter posts:
```{r,message=FALSE, include=TRUE}
total_sentiment_score <- function(tweets_sentiments, service_name){
tweet_table<-tweets_sentiments %>%
mutate(score = n*value)
sent.score_positive = case_when(
nrow(tweet_table)==0~0,
nrow(tweet_table)>0~sum(tweet_table[tweet_table$score>0,]$score)
)
sent.score_negative = case_when(
nrow(tweet_table)==0~0,
nrow(tweet_table)>0~sum(tweet_table[tweet_table$score<0,]$score)
)
positive_percent = sent.score_positive/(sent.score_positive+
abs(sent.score_negative))
negative_percent = abs(sent.score_negative)/(sent.score_positive+
abs(sent.score_negative))
results <- data.frame(c(service_name),c("Positive","Negative"),
c(positive_percent,negative_percent))
colnames(results) <- c("Service","Sentiment","Sentiment_Score")
return(results)
}
```
The sentiment analysis at the word level was performed for each ride service in order to have individual comparison for each of these services. Moreover, to have more aggregated comparison, the six services were reduced to four groups as the following: the Uber and Lyft services were grouped into one single group of App_Based Taxi, and the Amtrak and the Metro were grouped as Train transportation mode. The Figures 4 and 5 illustrate the results from the bing sentiment analysis for the six different services and the aggregated four groups.
```{r, echo=FALSE, message=FALSE, echo=FALSE}
Uber_word_sentiment <- total_sentiment_score(Uber.tweets_Sentiment, "1.Uber")
Lyft_word_sentiment <- total_sentiment_score(Lyft.tweets_Sentiment, "2.Lyft")
Taxi_word_sentiment <- total_sentiment_score(Taxi.tweets_Sentiment, "3.Taxi")
Amtrak_word_sentiment <- total_sentiment_score(Amtrak.tweets_Sentiment, "4.Amtrak")
metro_word_sentiment <- total_sentiment_score(metro.tweets_Sentiment, "5.Metro")
metrobus_word_sentiment <- total_sentiment_score(metrobus.tweets_Sentiment,"6.Metrobus")
word_sentiment_analysis_results <- rbind(Uber_word_sentiment,
Lyft_word_sentiment,
Taxi_word_sentiment,
Amtrak_word_sentiment,
metro_word_sentiment,
metrobus_word_sentiment)
word_sentiment_analysis_results %>%
ggplot(aes(x=Sentiment, y=Sentiment_Score, fill=Sentiment))+
geom_col(show.legend = T)+
geom_text(aes(label = paste0(round(Sentiment_Score*100, digits = 2),"%")), nudge_y = 0.05,size = 3)+
facet_wrap(~Service, scales = "free_x",as.table = TRUE)+
theme_bw()+
labs(caption = "Figure 4. Sentiment Analysis at the word level (6 categories)")+
theme(plot.caption = element_text(hjust = 0.5, size = 12))
```
```{r,message=FALSE, echo=FALSE}
AppBased_Taxi_word_sentiment <- total_sentiment_score(rbind(Uber.tweets_Sentiment,
Lyft.tweets_Sentiment),
"1.AppBased_Taxi")
Normal_Taxi_word_sentiment <- total_sentiment_score(Taxi.tweets_Sentiment,
"2.Normal_Taxi")
Train_word_sentiment <- total_sentiment_score(rbind(Amtrak.tweets_Sentiment,
metro.tweets_Sentiment),
"3.Train")
Bus_word_sentiment <- total_sentiment_score(metrobus.tweets_Sentiment,
"4.Bus")
word_sentiment_analysis_results <- rbind(AppBased_Taxi_word_sentiment,
Normal_Taxi_word_sentiment,
Train_word_sentiment,
Bus_word_sentiment)
word_sentiment_analysis_results %>%
ggplot(aes(x=Sentiment, y=Sentiment_Score, fill=Sentiment))+
geom_col(show.legend = T)+
geom_text(aes(label = paste0(round(Sentiment_Score*100, digits = 2),"%")), nudge_y = 0.05,size = 3)+
facet_wrap(~Service, scales = "free_x",as.table = TRUE)+
theme_bw()+
labs(caption = "Figure 5. Sentiment Analysis at the word level (4 categories)")+
theme(plot.caption = element_text(hjust = 0.5,size = 12))
```
## Text Ploarity Analysis using sentimentR
For the same six groups and the four groups defined before. The sentiment analysis was also done at the whole text level using the [-@sentimentr] package. The full text or the twitter post (after cleaning) was considered in the analysis instead of individual words. This can correct any inversion problem in the text. For example the bing sentiment would judge "I do not hate using Uber" as negative due the "hate" word, where in fact it is a positive opinion.
```{r, message=FALSE, include=TRUE}
Text_Polarity_Sentiment <- function(cleaned_data, service_name) {
sentiment_by(cleaned_data$text) %>%
mutate(Sentiment=case_when(
ave_sentiment==0~"Natural",
ave_sentiment<0~"Negative",
ave_sentiment>0~"Positive"
)) %>%
select(ave_sentiment,Sentiment) %>%
filter(Sentiment%in%c("Positive","Negative")) %>%
group_by(Sentiment) %>%
summarise(totals = sum(ave_sentiment), count = n())%>%
mutate(Sentiment_Score = count/sum(count)) %>%
select(Sentiment_Score, Sentiment) %>%
mutate(Service = service_name)
}
```
The Figures 6 and 7 show the results from the sentiment analysis at the text level using sentimentr package for the six different services and the aggregated four groups.
```{r, message=FALSE, echo=FALSE,warning=FALSE}
Uber_text_sentiment <- Text_Polarity_Sentiment(Uber.tweets, "1.Uber")
Lyft_text_sentiment <- Text_Polarity_Sentiment(Lyft.tweets, "2.Lyft")
Taxi_text_sentiment <- Text_Polarity_Sentiment(Taxi.tweets, "3.Taxi")
Amtrak_text_sentiment <- Text_Polarity_Sentiment(Amtrak.tweets, "4.Amtrak")
metro_text_sentiment <- Text_Polarity_Sentiment(metro.tweets, "5.Metro")
metrobus_text_sentiment <- Text_Polarity_Sentiment(metrobus.tweets,"6.Metrobus")
text_sentiment_analysis_results <- rbind(Uber_text_sentiment,
Lyft_text_sentiment,
Taxi_text_sentiment,
Amtrak_text_sentiment,
metro_text_sentiment,
metrobus_text_sentiment)
text_sentiment_analysis_results %>%
ggplot(aes(x=Sentiment, y=Sentiment_Score, fill=Sentiment))+
geom_col(show.legend = T)+
geom_text(aes(label = label_percent()(Sentiment_Score) ), nudge_y = 0.05,size = 3)+
facet_wrap(~Service, scales = "free_x",as.table = TRUE)+
theme_bw()+
labs(caption = "Figure 6. Sentiment Analysis per the whole text (6 categories)")+
theme(plot.caption = element_text(hjust = 0.5,size = 12))
```
```{r, message=FALSE, echo=FALSE,warning=FALSE}
AppBased_Taxi_text_sentiment <- Text_Polarity_Sentiment(rbind(Uber.tweets,
Lyft.tweets),
"1.AppBased_Taxi")
Normal_Taxi_text_sentiment <- Text_Polarity_Sentiment(Taxi.tweets,
"2.Normal_Taxi")
Train_text_sentiment <- Text_Polarity_Sentiment(rbind(Amtrak.tweets,
metro.tweets),
"3.Train")
Bus_text_sentiment <- Text_Polarity_Sentiment(metrobus.tweets,
"4.Bus")
text_sentiment_analysis_results <- rbind(AppBased_Taxi_text_sentiment,
Normal_Taxi_text_sentiment,
Train_text_sentiment,
Bus_text_sentiment)
text_sentiment_analysis_results %>%
ggplot(aes(x=Sentiment, y=Sentiment_Score, fill=Sentiment))+
geom_col(show.legend = T)+
geom_text(aes(label = label_percent()(Sentiment_Score) ), nudge_y = 0.05,size = 3)+
facet_wrap(~Service, scales = "free_x",as.table = TRUE)+
theme_bw()+
labs(caption = "Figure 7. Sentiment Analysis per the whole text (4 categories)")+
theme(plot.caption = element_text(hjust = 0.5,size = 12))
```
# Results
In general, the sentiment analysis at the word level (Figures 4 and 5) did not show any strong opinion towrd any of the feelings (positive or negative) and had slightly differences in the percentages among the different services. However, the results showed that the App based services (Uber & Lyft) had more positive opinions than the normal cab taxi. Similarly, the Metro and Amtrak results had higher percentages of the positive feelings than the Metrobus. Moreoever, the results showed more negative opinions toward the provided services with no significant differences in the percentages among all the services.
On the other hand, the sentiment analysis at the word level showed that the twitter posts had more likely positive opinions toward these ride services expect for the normal cab taxi as shown in Figures 6. Overall, the relative comparisons between the services was noticed to be the same or very close between the two method of the sentiment analysis. For example, the normal cab taxi was always accompanied with the highest negative opinions and the lowest positive opinions. Therefore, the services were ranked from the most likely service to the lowest based on the positive percentages results from both methods. It was found that both of the two methods had captured very similar ranks for the selected services. Figures 8 and 9 summaries the ranks for each service or a group of service for each sentiment analysis method.
```{r, message=FALSE, echo=FALSE}
Overall_word_sentiment_results <- rbind(Uber_word_sentiment,
Lyft_word_sentiment,
Taxi_word_sentiment,
Amtrak_word_sentiment,
metro_word_sentiment,
metrobus_word_sentiment) %>%
filter(Sentiment%in%c("Positive")) %>%
mutate(Service = gsub('[.]', '', gsub('[0-9]+', '', .$Service)))%>%
arrange(desc(Sentiment_Score)) %>%
mutate(Service = fct_reorder(Service, Sentiment_Score)) %>%
mutate(Rank = 1:n()) %>%
ggplot(aes(Service, Sentiment_Score, fill=Service))+
geom_col(show.legend = F)+
geom_text(aes(label = Rank ), nudge_y = 0.025,size = 3)+
ggtitle("Sentiment Per Word")+
coord_flip()+
theme_bw()
Overall_text_sentiment_results <- rbind(Uber_text_sentiment,
Lyft_text_sentiment,
Taxi_text_sentiment,
Amtrak_text_sentiment,
metro_text_sentiment,
metrobus_text_sentiment) %>%
filter(Sentiment%in%c("Positive")) %>%
mutate(Service = gsub('[.]', '', gsub('[0-9]+', '', .$Service)))%>%
arrange(desc(Sentiment_Score)) %>%
mutate(Service = fct_reorder(Service, Sentiment_Score)) %>%
mutate(Rank = 1:n()) %>%
ggplot(aes(Service, Sentiment_Score, fill=Service))+
geom_col(show.legend = F)+
geom_text(aes(label = Rank ), nudge_y = 0.025,size = 3)+
ggtitle("Sentiment Per Text")+
coord_flip()+
theme_bw()
grid.arrange(Overall_word_sentiment_results, Overall_text_sentiment_results, ncol=2,
bottom ="Figure 8. Ride services in D.C. from the most prefered to the least")
```
```{r, message=FALSE, echo=FALSE}
Overall_word_sentiment_results <- rbind(AppBased_Taxi_word_sentiment,
Normal_Taxi_word_sentiment,
Train_word_sentiment,
Bus_word_sentiment) %>%
filter(Sentiment%in%c("Positive")) %>%
mutate(Service = gsub('[.]', '', gsub('[0-9]+', '', .$Service)))%>%
arrange(desc(Sentiment_Score)) %>%
mutate(Service = fct_reorder(Service, Sentiment_Score)) %>%
mutate(Rank = 1:n()) %>%
ggplot(aes(Service, Sentiment_Score, fill=Service))+
geom_col(show.legend = F)+
geom_text(aes(label = Rank ), nudge_y = 0.025,size = 3)+
ggtitle("Sentiment Per Word")+
coord_flip()+
theme_bw()
Overall_text_sentiment_results <- rbind(AppBased_Taxi_word_sentiment,
Normal_Taxi_word_sentiment,
Train_word_sentiment,
Bus_word_sentiment) %>%
filter(Sentiment%in%c("Positive")) %>%
mutate(Service = gsub('[.]', '', gsub('[0-9]+', '', .$Service)))%>%
arrange(desc(Sentiment_Score)) %>%
mutate(Service = fct_reorder(Service, Sentiment_Score)) %>%
mutate(Rank = 1:n()) %>%
ggplot(aes(Service, Sentiment_Score, fill=Service))+
geom_col(show.legend = F)+
geom_text(aes(label = Rank ), nudge_y = 0.025,size = 3)+
ggtitle("Sentiment Per Text")+
coord_flip()+
theme_bw()
grid.arrange(Overall_word_sentiment_results, Overall_text_sentiment_results, ncol=2,
bottom ="Figure 9. Ride service from the most prefered to the least")
```
# Conclusion
This research study involves sentiment analysis towards the use of public transportation and ride-sharing services in the Washington D.C area. The data was collected through Twitter API for November 2021 (11-02-2021 to 12-02-2021). The collected data included the entire D.C. area and some parts of Baltimore since several people live there and work in D.C. The study included several public transportations such as Amtrak, Metrobus, and the Metro and some common ridesharing services including Uber, Lyft, and the normal cab-taxi. The sentiment analysis was done at the word level using the "tidytext" package and per the whole text using the "bing" dictionary. The results showed that both of the methods can be used to measure the same relative comparison between the service. However, the two methods had opposite opinions about each service.
\newpage
# References