-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
executable file
·856 lines (638 loc) · 31.7 KB
/
index.html
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
<!DOCTYPE html>
<html lang="" xml:lang="">
<head>
<title>MAT381E-Week 9: Data Retrieval from Twitter</title>
<meta charset="utf-8" />
<meta name="author" content="Gül İnan" />
<meta name="date" content="2021-12-06" />
<script src="intro_social_media_files/header-attrs-2.11/header-attrs.js"></script>
<link href="intro_social_media_files/remark-css-0.0.1/default.css" rel="stylesheet" />
<script src="intro_social_media_files/fabric-4.3.1/fabric.min.js"></script>
<link href="intro_social_media_files/xaringanExtra-scribble-0.0.1/scribble.css" rel="stylesheet" />
<script src="intro_social_media_files/xaringanExtra-scribble-0.0.1/scribble.js"></script>
<script>document.addEventListener('DOMContentLoaded', function() { window.xeScribble = new Scribble({"pen_color":["#FF0000"],"pen_size":3,"eraser_size":30,"palette":[]}) })</script>
<link href="intro_social_media_files/tile-view-0.2.6/tile-view.css" rel="stylesheet" />
<script src="intro_social_media_files/tile-view-0.2.6/tile-view.js"></script>
<link href="intro_social_media_files/animate.css-3.7.2/animate.xaringan.css" rel="stylesheet" />
<link href="intro_social_media_files/tachyons-4.12.0/tachyons.min.css" rel="stylesheet" />
<link href="intro_social_media_files/panelset-0.2.6/panelset.css" rel="stylesheet" />
<script src="intro_social_media_files/panelset-0.2.6/panelset.js"></script>
<link rel="stylesheet" href="xaringan-themer.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: left, middle, my-title, title-slide
# MAT381E-Week 9: Data Retrieval from Twitter
### Gül İnan
### Department of Mathematics<br/>Istanbul Technical University
### December 6, 2021
---
# Outline
* Data retrieval from Twitter.
* 01_rtweet.Rmd (hands-on, in class).
---
### Social Media Data
- **Social media data** typically describes information created and curated by individual users and collected using public platforms such as Twitter, Facebook, Instagram, YouTube, Snapchat, and many other social media networks.
- Social media data can be a **powerful source of information** given it can provide a near **real-time outlook** on both social events such as **politics**, **current day events** (financial events, military events, and social movements) and natural processes including **weather events** (rainfall, snow), **disturbances** (earthquakes, floods, and other natural disasters), and more.
---
#### Challenges Working with Social Media Data
- There are many challenges associated with social media data including:
- **Non standard text:** because social media data are often a combination of text, graphics and videos, there is a significant data cleaning involved. Often, you need to find information about something in non-standard text format - some words may be capitalized, abbreviations may be used, punctuation and even emojiis all have to be considered when working with text.
- **Non-standard or lack of consistent geolocation information:** Not all social media is spatially located (geolocated). It is thus often tricky to figure out where the data are coming from. Sometimes you have some geolocation information in non-standard text formats - for instance İstanbul may be in the forms: İst, IST, ISTANBUL and so on.
- **API limitations:** Most APIs don’t allow users to download everything. In the case of Twitter, you are limited to 6-9 days of historical tweets, 18,000 tweets per API call. There is also restriction on the number of requests you are allowed to do which is based on a time interval such as 15-minutes.
---
#### 💡 A side note: Getting Data from Internet
- There are a few ways to obtain data from the Internet:
- **Click and download data** on the internet as a flat file such as `.csv` or `.xls`,
- **Scrape** a website, and
- **Use APIs** (standard APIs or APIs possibly wrapped within a software package).
---
class: middle, center
<img src="images/apitwitter.png" width="80%" height="100%" />
---
#### Application Program Interfaces (APIs)
- **API** is an acronym for **Application Programming Interface**, which is an intermediate software that allows two applications to talk to each other.
#### Example
- When you use an application on your mobile phone (i.e., searching flights on an online travel service such as Kayak or Expedia), the application connects to the Internet and sends data (i.e., departure and return cities and dates and more) to a server (databases of several airlines).
- The server then retrieves that data, interprets it, performs the necessary actions (i.e., book seats, adjust baggage options, etc) and sends it back to your phone (i.e., your travel itinerary).
- The application which interprets that data and presents you with the information you wanted in a readable way happens via API.
[Source](https://www.mulesoft.com/resources/api/what-is-an-api)
---
- As any other piece of productized software, the **modern API has its own software development lifecycle** of designing, testing, building, managing, and versioning.
- Also, modern APIs are **well documented** for consumption and versioning.
---
#### Twitter
- According to Wikipedia:
>
Twitter is a social networking and microblogging service. Users use any device with an internet connection and a web browser to send and to read messages, called "tweets". For years, tweets could be up to 140 characters long, then doubled in November 2017 to 280 characters. They appear on the user's profile page. Tweets can usually be read by anyone, but senders can also keep messages private. Private tweets only go to their list of friends. Users may subscribe to tweets from other people. This is called **following**, and subscribers are known as **followers**.
>
- Many people use Twitter to discuss on any topic. These topics may be related anything of interest and may including: **science**, **data science**, **computing**, sports, politics, weather, news, media, and more.
---
<a href="https://developer.twitter.com/en/products/twitter-api" target="_blank"><img src="images/twitter_api.png" width="1776" height="20%" /></a>
[Source](https://developer.twitter.com/en/products/twitter-api)
---
<a href="https://twitterdev.bevylabs.com/istanbul-twitter-developer-community/" target="_blank"><img src="images/twitter_istanbul_api.png" width="1895" height="30%" /></a>
[Source](https://twitterdev.bevylabs.com/istanbul-twitter-developer-community/)
---
<a href="https://twitterdev.bevylabs.com/events/details/twitter-istanbul-twitter-developer-community-presents-deep-dive-tutorial-on-twitter-academic-api-usage/" target="_blank"><img src="images/istanbul_meeting.png" width="1728" height="30%" /></a>
[Source](https://twitterdev.bevylabs.com/events/details/twitter-istanbul-twitter-developer-community-presents-deep-dive-tutorial-on-twitter-academic-api-usage/)
---
#### Collecting Social Media Data
- The general procedure for working with social media data includes the following steps:
- Learn about platform's specific requirements in relation to data collection, privacy, and data management.
- Learn about the platform's `API` rules.
- Social media rules change too quickly and social platform may not tell you about changes done and announce them only after!
---
<a href="https://developer.twitter.com/en/developer-terms/more-on-restricted-use-cases" target="_blank"><img src="images/twitter_privacy.png" width="1735" height="5%" /></a>
---
class: middle, center
# Collecting Data via Twitter
---
#### Collecting Data via Twitter
1. To connect to Twitter, you need to have a `Twitter account`.
2. You can create it [here](https://twitter.com/signup).
You need to note down your `username` and `password`.
3. You may need developers' access key if you want to work with `Twitter API` directly or use R package `rtweet`.
---
#### Collecting Data via Twitter standard API
<a href="https://developer.twitter.com/en/use-cases/do-research" target="_blank"><img src="images/twitter_dev.png" width="1768" height="50%" /></a>
---
#### Get Twitter API Developer Key
<a href="https://developer.twitter.com/en/portal/petition/essential/basic-info" target="_blank"><img src="images/developer.png" width="1839" height="50%" /></a>
---
class: middle, center
# rtweet
<img src="logo/rtweet.png" width="30%" height="100%" />
---
# rtweet package
- The [rtweet package](https://docs.ropensci.org/rtweet/) provides users a range of functions designed to extract data from Twitter’s APIs.
- Conveniently, we **do need a Twitter account** only.
- First, to be able to use the functionality of `rtweet` package, we have to install and load the package:
```r
#install.packages("rtweet")
library(rtweet)
```
---
- As a next step, we need to approve the browser pop-up and it will create a token and need to save it for future use (as far as i see you need to do this only once per machine).
<img src="images/auth.png" width="60%" height="100%" />
---
#### Access tokens: Problems with above?
- If you were unable to authenticate with the Twitter API, you will need to use the `rwteet::create_token()` function. Read more about obtaining and using tokens. **Specifically**, see under the authorization methods, section 2: [_Access token/secret method_](https://docs.ropensci.org/rtweet/articles/auth.html#access-tokensecret-method).
---
- Some most useful functions in `rtweet` package include:
|Function | Description |
|-------------------|------------------------------------------------------------------|
|`search_users()` | getting users data on accounts identified via search query. |
|`search_tweets()` | getting tweets data on statuses identified via search query. |
|`ts_plot()` | plotting tweets data as a time series-like data object. |
|`get_friends()` | getting user IDs of accounts followed by target user(s). |
|`get_followers()` | getting user IDs for accounts following target user. |
|`get_timeline()` | getting one or more user timelines (tweets posted by target user(s)).|
|`get_favorites()` | getting tweets data for statuses favorited by one or more target users.| |
|`get_trends()` | getting Twitter trends data. |
---
#### Find Twitter users: search_users()
- The function `search_users(q, n)` enables us to search for Twitter users by interest, full name, company name, or location (exact match searches are not supported).
- In the following example, `search_users(q, n)` will locate first 1000 Twitter users who Tweeted about **artificial intelligence**.
```r
ai_lovers <- search_users(q = "artificial intelligence", n = 1000)
#returns the latest tweets of the users who mentioned about AI sometime.
#search can be done over Twitter profiles as well.
#View(ai_lovers)
```
- Some of input arguments:
- `q`: Should be a character string not to exceed 500 characters maximum. Spaces are assumed to function like Boolean "AND" operators. For example, the search query = "data science" searches for tweets using both "data" and "science" though the words can appear anywhere and in any order in the tweet. To search for tweets including one of multiple possible terms, separate search terms with spaces and the word "OR". **Go to the help menu for more details!..**
- `n`: Numeric, specifying the total number of desired users to return. Default is 100. Maximum number of users returned from a single search is 1,000.
---
<style type="text/css">
.pull-left {
float: left;
width: 50%;
}
.pull-right {
float: right;
width: 50%;
}
</style>
- Two examples returned with screen names are: **MIT_CSAIL** and **nordicinst**, respectively:
.pull-left[
<img src="images/mit_csail.png" width="100%" height="100%" />
]
.pull-right[
<img src="images/naii.png" width="100%" height="100%" />
]
---
#### Results
- Gathering Tweeter users will return a **90 variable tibble** with row size of at most **n**. Now, please spend some time to get familiar with these variables.
```r
library(tibble)
class(ai_lovers)
glimpse(ai_lovers)
# The type of "created_at" variable is defined as <dttm>.
# Tibbles print date as <dttm>. Elsewhere in R these are called POSIXct.
```
- Some of the returned variables are:
- **user_id:** Twitter user id.
- **status_id:** Twitter id of the last tweet.
- **created_at:** Date-time of the last tweet.
- **screen_name:** Twitter user name.
- **text:** Text of the last tweet.
- **source:** The platform where the last tweet is sent from.
- **display_text_width:** Character length of the last tweet (the limit is 280 characters).
---
#### 💡 A side note:
- If you are interested in `Twitter character counts` more, take
a look at this article:
<img src="images/twitter_character.png" width="70%" height="100%" />
[Source](https://developer.twitter.com/en/docs/counting-characters)
---
#### Collect data: search_tweets()
- The function `search_tweets(q, n, retryonratelimit)` enables us to search tweets with a query, however only last 6-9 days can be collected.
- Let's find out tweets mentioning about **artificial intelligence**:
```r
### recommended: limit the number of tweets returned (`n = 100`) for this training.
#### Otherwise you may hit a rate limit.
ai_tweets <- search_tweets(q = "artificial intelligence", n = 100)
```
- Some of input arguments:
- `q`: Query to be searched, used to filter and select tweets. Should be a character string not to exceed 500 characters maximum. Spaces are assumed to function like boolean "AND" operators. **Go to the help menu for more details!..**
- `n`: Integer number of tweets to return. The default is 100. The max is 18,000.
- `retryonratelimit`: The default is FALSE. Set to TRUE to search more than 18,000. For popular topics, the total number of tweets window of time (7-10 days) can easily reach the millions.
- `include_rts = FALSE`: Exclude retweets.
- `lang = "en" `: Language in English.
- `lang = "tr" `: Language in Turkish.
- `geocode`: Geographical limiter. Limits search results to "latitude, longitude". For example, `geocode = "41.015137,28.979530,100mi"` limit search results to Istanbul.
---
```r
#search tweets about artificial intelligence in turkish tweets
ai_tweets_tr <- search_tweets(q = "artificial intelligence", n = 100, lang = "tr")
colnames(ai_tweets_tr)
ai_tweets_tr %>% select("text") %>% .[1,]
```
```r
#search tweets about yapay zeka around istanbul
yz <- search_tweets(q = "yapay zeka", geocode = "41.015137,28.979530,100mi")
```
---
<img src="images/rate_limit.png" width="100%" height="100%" />
[Source](https://developer.twitter.com/en/docs/twitter-api/rate-limits)
---
- 💡 Twitter API documentation recommends limiting searches to 10 keywords and operators.
- Some more examples on `Twitter` search queries (none of these are case sensitive):
| Search Query | Tweets ... |
|----------------------------------|--------------------------------------------------------|
| "artificial intelligence" | includes both "artificial" and "intelligence", words can appear in any order in the tweet. |
| "artificial OR intelligence" | returns **any tweet** including either "artificial" or "intelligence".|
|'"artificial intelligence"' | returns tweets containing exact phrase. |
| "\"artificial intelligence\"" | return tweets containing exact phrase.
---
<style type="text/css">
.pull-left {
float: left;
width: 50%;
}
.pull-right {
float: right;
width: 50%;
}
</style>
- More on Twitter query operators:
.pull-left[
<img src="images/query1.png" width="100%" height="100%" />
]
.pull-right[
<img src="images/query2.png" width="100%" height="100%" />
]
[Source-page 59](https://cran.r-project.org/web/packages/rtweet/rtweet.pdf)
---
#### Plot the retrieved data: ts_plot()
.panelset[
.panel[.panel-name[Code]
- The function `ts_plot(data, by)` creates a `ggplot2` plot of the frequency of tweets over a specified interval of time (you can check the class of the plot object).
- Let's plot the number of tweets mentioning the official Twitter account of ITU: "@itu1773" over the past days.
```r
####plot 1
itu_search <- search_tweets(q = "@itu1773", n = 10000)
ts_plot(data = itu_search, by="days")
```
- Some of the input arguments:
- `data`: Data frame or grouped data frame.
- `by`: Desired interval of time expressed as numeral plus one of "secs", "mins", "hours",
"days", "weeks", "months", or "years". If a numeric is provided, the value is assumed to be in seconds.
- `...`: Other arguments passed to `geom_line()`.
]
.panel[.panel-name[Output]
<img src="intro_social_media_files/figure-html/unnamed-chunk-25-1.png" width="40%" />
]
]
---
.panelset[
.panel[.panel-name[Code]
- If `ggplot2` is loaded then, `ts_plot()` is actually returns a `ggplot2` plot object.
```r
class(ts_plot(data = itu_search, by = "days"))
```
- Let's group the tweets to compare by language.
```r
####plot 2
library(ggplot2)
itu_search %>%
#mutate(created_at = as.Date(created_at)) %>%
dplyr::group_by(lang) %>%
ts_plot(by="days") +
labs(title = "Number of Tweets mentioning @itu1773 over time",
subtitle = "Tweets are collected over December 2021",
caption = "\nSource: Data collected from Twitter's REST API via rtweet",
x = "Days", y = "Frequency",
color = "Language") +
scale_y_continuous(limits = c(0, 60)) +
#scale_x_date(position = "top") + #did not work
#I opened an issue at: https://github.com/ropensci/rtweet/issues/573#issuecomment-825999849
theme_minimal() +
theme(legend.title = element_blank(),
legend.position = "bottom",
plot.title = element_text(face = "bold"))
```
]
.panel[.panel-name[Output]
<img src="intro_social_media_files/figure-html/unnamed-chunk-28-1.png" width="40%" />
]
]
---
#### get friends
- The function `get_friends(users, n)` returns a list of user IDs for the accounts following BY one or more specified users.
- Let's find all the accounts which **itu1773 user** follows:
```r
itu_friends <- get_friends("itu1773")
#View(itu_friends)
```
- Some of the input arguments:
- `users`: Screen name or user ID of target user.
- `n`: Number of friends (user IDs) to return. Defaults to 5,000.
- It returns a data frame with target user screen name and user IDs of friends (accounts followed BY target user).
---
- Next, use `lookup_users()` with the `user_id` variable to get **more information about those accounts**.
```r
itu_friend_data <- lookup_users(itu_friends$user_id)
#View(itu_friend_data)
```
- Let's get the screen names of the user accounts.
```r
library(dplyr)
#get the screen names of the users
itu_friend_names <- itu_friend_data %>%
select(screen_name)
#View(itu_friend_names)
```
---
- A recent example: get user ids of accounts followed by Donald Trump.
```r
djt <- get_friends("realDonaldTrump")
djt
```
```
## # A tibble: 0 × 0
```
--
.pull-right[
<img src="images/djt.png" width="100%" height="100%" />
[Source](https://blog.twitter.com/en_us/topics/company/2020/suspension.html)
]
---
#### get followers
- The function `get_followers(user, n)` returns a list of user IDs for the accounts following specified user.
- Let's find all the accounts which follows **itu1773 user**:
```r
follow_itu <- get_followers(user="itu1773")
#returns most recent 5000 followers
#View(follow_itu)
```
```r
##if you have run the previous code, wait a couple of minutes prior to
##running the code below:
#follow_itu <- get_followers(user="itu1773", retryonratelimit = TRUE)
#View(follow_itu)
```
- Some of the input arguments:
- `users`: Screen name or user ID of target user from which the user IDs of followers will be retrieved.
- `n`: Number of friends (user IDs) to return. Defaults to 5,000.
- It returns a data frame with user IDs of followers.
---
- Next, use `lookup_users()` with the `user_id` variable to get more information about those accounts.
```r
#be careful, it is too slow, may not response immediately.
itu_follower_data <- lookup_users(follow_itu$user_id)
#View(itu_follower_data)
```
---
#### get timelines
- The function `get_timelines(user, n)` returns up to 3,200 statuses posted to the timelines of each of one or more specified Twitter users.
- Let's find latest posts of **itu1773 user**:
```r
itu_tmls <- get_timelines("itu1773", n = 210)
#View(itu_tmls)
```
- Some of the input arguments:
- `users`: Vector of user names, user IDs, or a mixture of both.
- `n`: Number of tweets to return per timeline. Defaults to 100.
- It returns a tbl data frame of tweets data with users.
---
- Check the time interval in the data.
```r
library(dplyr)
itu_tmls %>%
summarise(min(created_at), max(created_at))
```
```
## # A tibble: 1 × 2
## `min(created_at)` `max(created_at)`
## <dttm> <dttm>
## 1 2021-08-06 08:28:44 2021-12-06 10:47:18
```
---
<style type="text/css">
.pull-left {
float: left;
width: 60%;
}
.pull-right {
float: right;
width: 35%;
}
</style>
.pull-left[
- Let's see what itu1773 user shared on October 29, 2021!..🇹🇷🇹🇷
```r
library(dplyr)
library(lubridate)
republic_day <- itu_tmls %>%
mutate(created_at = date(created_at)) %>%
filter(created_at == ymd("2021-10-29")) %>%
select(text) %>% .[2,] %>%
as.data.frame()
knitr::kable(republic_day, col.names="")
```
| |
|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|Bağımsızlığımızın teminatı olan ve ülkemizin kuruluşunu temsil eden Cumhuriyetimiz bugün 98 yaşında… Cumhuriyetimizin kurucusu Gazi Mustafa Kemal Atatürk’ü ve silah arkadaşlarını saygı ve minnetle anıyoruz. #29EkimCumhuriyetBayramı’mız kutlu olsun! 🇹🇷 https://t.co/52Dx8GUjum |
]
--
.pull-right[
<blockquote class="twitter-tweet"><p lang="tr" dir="ltr">Bağımsızlığımızın teminatı olan ve ülkemizin kuruluşunu temsil eden Cumhuriyetimiz bugün 98 yaşında… Cumhuriyetimizin kurucusu Gazi Mustafa Kemal Atatürk’ü ve silah arkadaşlarını saygı ve minnetle anıyoruz. <a href="https://twitter.com/hashtag/29EkimCumhuriyetBayram%C4%B1?src=hash&amp;ref_src=twsrc%5Etfw">#29EkimCumhuriyetBayramı</a>’mız kutlu olsun! 🇹🇷 <a href="https://t.co/52Dx8GUjum">pic.twitter.com/52Dx8GUjum</a></p>&mdash; İTÜ - İstanbul Teknik Üniversitesi (@itu1773) <a href="https://twitter.com/itu1773/status/1453964833720717315?ref_src=twsrc%5Etfw">October 29, 2021</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
]
---
#### get_favorites
- The function `get_favorites(user, n)` returns up to 3,000 statuses favorited by each of one or more specific Twitter users.
```r
itu_faves <- get_favorites("itu1773", n = 1000)
#View(itu_faves)
```
```r
#Guess who is the user most liked by itu1773?
library(dplyr)
itu_faves %>%
group_by(screen_name) %>%
summarize(n=n()) %>%
top_n(5)
```
---
#### get trends
- The function `get_trends(woeid, n)` returns up to 3,000 statuses favorited by each of one or more specific Twitter users.
- What is trending in İstanbul?
```r
ist <- get_trends("istanbul")
#ist <- get_trends(2344116) #WOEID of Istanbul
#istanbul <- get_trends(lat = 41.015137, lng = 28.979530)
#View(ist)
```
- Some of the input arguments:
- `woeid`: Numeric, WOEID (Yahoo! Where On Earth ID) or character string of desired town or country. Users may also supply latitude and longitude coordinates to fetch the closest available trends data given the provided location. To find WOEID IDs, go to the https://www.yahoo.com/news/weather/ and search for the city. WOEID will be at the end of the url of the page.
- `lat`: Optional alternative to WOEID.
- `lng`: Optional alternative to WOEID.
- It returns a tibble data frame of trends data for a given geographical area.
---
```r
#cautionary note: query results are the trending
#topics in Istanbul at the time of query. I do not take
#any responsibility
#for the query results.
ist %>%
arrange(tweet_volume)
```
---
class: center
<style type="text/css">
.pull-left {
float: left;
width: 50%;
}
.pull-right {
float: right;
width: 50%;
}
</style>
#### Academic Research with Twitter Data
.pull-left[
<blockquote class="twitter-tweet"><p lang="en" dir="ltr">Students &amp; researchers, we have something new for you. 🌟<br> <br>Introducing a new 101 course designed to help you start with academic research using the <a href="https://twitter.com/hashtag/TwitterAPI?src=hash&amp;ref_src=twsrc%5Etfw">#TwitterAPI</a> v2. 📖 <br><br>Complete with cheat sheets and code samples in Python and R, so you can plug and play. <a href="https://t.co/ugh9Md6ADN">https://t.co/ugh9Md6ADN</a> <a href="https://t.co/FaZN1Y8WwJ">pic.twitter.com/FaZN1Y8WwJ</a></p>&mdash; Twitter Dev (@TwitterDev) <a href="https://twitter.com/TwitterDev/status/1409931481552543749?ref_src=twsrc%5Etfw">June 29, 2021</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
]
.pull-right[
<img src="images/twitter_academic_search.png" width="100%" height="100%" />
[Source](https://developer.twitter.com/en/solutions/academic-research)
]
---
class: center, middle
<a href="https://developer.twitter.com/en/portal/petition/academic/is-it-right-for-you" target="_blank"><img src="images/twitter2.png" width="100%" height="100%" /></a>
[Source](https://developer.twitter.com/en/portal/petition/academic/is-it-right-for-you)
]
---
class: center, middle
<img src="images/covid19.png" width="100%" height="100%" />
---
<style type="text/css">
.pull-left {
float: left;
width: 45%;
}
.pull-right {
float: right;
width: 45%;
}
</style>
#### Facebook and YouTube
.pull-left[
<img src="images/facebook1.png" width="100%" height="100%" />
[Source](https://migrationdataportal.org/data-innovation-46)
]
.pull-right[
<img src="images/youtube1.png" width="100%" height="100%" />
[Source](https://www.db-thueringen.de/servlets/MCRFileNodeServlet/dbt_derivate_00049346/2192-4007_9_2020_1_62-88.pdf)
]
---
# Attributions
- [Twitter data retrieval](https://raw.githubusercontent.com/maria-pro/useR2019_tutorial/master/Twitter.Rmd).
- [Recipes for Mining Twitter Data with rtweet](https://rud.is/books/21-recipes/).
- [Use Twitter Social Media Data in Python](https://www.earthdatascience.org/courses/use-data-open-source-python/intro-to-apis/social-media-text-mining-python/)
</textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script>var slideshow = remark.create({
"highlightStyle": "github",
"highlightLines": true,
"countIncrementalSlides": false,
"ratio": "16:9",
"navigation": {
"scroll": false
}
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function(d) {
var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
if (!r) return;
s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
d.head.appendChild(s);
})(document);
(function(d) {
var el = d.getElementsByClassName("remark-slides-area");
if (!el) return;
var slide, slides = slideshow.getSlides(), els = el[0].children;
for (var i = 1; i < slides.length; i++) {
slide = slides[i];
if (slide.properties.continued === "true" || slide.properties.count === "false") {
els[i - 1].className += ' has-continuation';
}
}
var s = d.createElement("style");
s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
var deleted = false;
slideshow.on('beforeShowSlide', function(slide) {
if (deleted) return;
var sheets = document.styleSheets, node;
for (var i = 0; i < sheets.length; i++) {
node = sheets[i].ownerNode;
if (node.dataset["target"] !== "print-only") continue;
node.parentNode.removeChild(node);
}
deleted = true;
});
})();
(function() {
"use strict"
// Replace <script> tags in slides area to make them executable
var scripts = document.querySelectorAll(
'.remark-slides-area .remark-slide-container script'
);
if (!scripts.length) return;
for (var i = 0; i < scripts.length; i++) {
var s = document.createElement('script');
var code = document.createTextNode(scripts[i].textContent);
s.appendChild(code);
var scriptAttrs = scripts[i].attributes;
for (var j = 0; j < scriptAttrs.length; j++) {
s.setAttribute(scriptAttrs[j].name, scriptAttrs[j].value);
}
scripts[i].parentElement.replaceChild(s, scripts[i]);
}
})();
(function() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
links[i].target = '_blank';
}
}
})();
// adds .remark-code-has-line-highlighted class to <pre> parent elements
// of code chunks containing highlighted lines with class .remark-code-line-highlighted
(function(d) {
const hlines = d.querySelectorAll('.remark-code-line-highlighted');
const preParents = [];
const findPreParent = function(line, p = 0) {
if (p > 1) return null; // traverse up no further than grandparent
const el = line.parentElement;
return el.tagName === "PRE" ? el : findPreParent(el, ++p);
};
for (let line of hlines) {
let pre = findPreParent(line);
if (pre && !preParents.includes(pre)) preParents.push(pre);
}
preParents.forEach(p => p.classList.add("remark-code-has-line-highlighted"));
})(document);</script>
<script>
slideshow._releaseMath = function(el) {
var i, text, code, codes = el.getElementsByTagName('code');
for (i = 0; i < codes.length;) {
code = codes[i];
if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
text = code.textContent;
if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
/^\$\$(.|\s)+\$\$$/.test(text) ||
/^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
code.outerHTML = code.innerHTML; // remove <code></code>
continue;
}
}
i++;
}
};
slideshow._releaseMath(document);
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML';
if (location.protocol !== 'file:' && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
</body>
</html>