Extracting Tweets

Retrieve tweets from Twitter

# Load packages
library(rtweet)
library(tidyverse)
# Twitter authentication
create_token(
  app             = "behumble_please",
  consumer_key    = consumer_key,
  consumer_secret = consumer_secret,
  access_token    = access_token,
  access_secret   = access_secret)
## <Token>
## <oauth_endpoint>
##  request:   https://api.twitter.com/oauth/request_token
##  authorize: https://api.twitter.com/oauth/authenticate
##  access:    https://api.twitter.com/oauth/access_token
## <oauth_app> behumble_please
##   key:    OakS8ZIhrXK0l30ZZ9lBXlKxT
##   secret: <hidden>
## <credentials> oauth_token, oauth_token_secret
## ---

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

# Retrieve tweets
tweets <- search_tweets("#PKM", n = 1000, tweet_mode="extended")
## Searching for tweets...
## Finished collecting tweets!
tweets <- distinct(tweets, text, .keep_all=TRUE)

Tweets Description

## plot time series of tweets
ts_plot(tweets, "3 hours") +
  theme_minimal() +
  theme(plot.title = ggplot2::element_text(face = "bold")) +
  labs(
    x = NULL, y = NULL,
    title = "Frequency of #Knowledges Twitter statuses from past 9 days",
    subtitle = "Twitter status (tweet) counts aggregated using 3 hours",
    caption = "\nSource: Data collected from Twitter's REST API via rtweet"
  )

tail(tweets, 20)
## # A tibble: 20 x 88
##    user_id status_id created_at          screen_name text  source
##    <chr>   <chr>     <dttm>              <chr>       <chr> <chr> 
##  1 365680~ 10610385~ 2018-11-09 23:31:08 RogueGunn   from~ Insta~
##  2 365680~ 10595657~ 2018-11-05 21:58:44 RogueGunn   @Reg~ Insta~
##  3 811722~ 10610307~ 2018-11-09 23:00:27 TheBrianHo~ "Whi~ Buffer
##  4 884343~ 10608621~ 2018-11-09 11:50:14 umeadipat   Toda~ Twitt~
##  5 302142~ 10608121~ 2018-11-09 08:31:39 wyborcza3m~ Szyk~ Twitt~
##  6 200480~ 10606616~ 2018-11-08 22:33:39 iamstanley~ Have~ Twitt~
##  7 195496~ 10603952~ 2018-11-08 04:55:14 mustajar3   "OTW~ Faceb~
##  8 951091~ 10602755~ 2018-11-07 20:59:20 NigeriaCap~ "@Mo~ Twitt~
##  9 162705~ 10601818~ 2018-11-07 14:46:55 GentleOddy  A vo~ Twitt~
## 10 976416~ 10598374~ 2018-11-06 15:58:30 inxpirius   By @~ Twitt~
## 11 174905~ 10594853~ 2018-11-05 16:39:36 juandoming  netw~ Scoop~
## 12 160906~ 10598039~ 2018-11-06 13:45:18 Axel_Fisch~ "#Pa~ Insta~
## 13 111474~ 10596088~ 2018-11-06 00:50:21 Mik3Limon   "@pa~ Twitt~
## 14 689976~ 10595953~ 2018-11-05 23:56:37 bowdenarti~ As #~ Twitt~
## 15 907764~ 10594040~ 2018-11-05 11:16:31 enymariani  "Eva~ Insta~
## 16 988100~ 10592027~ 2018-11-04 21:56:24 whatacomeb~ Qiya~ Twitt~
## 17 196803~ 10591779~ 2018-11-04 20:17:59 PortalAcon~ "Um ~ Faceb~
## 18 105033~ 10583099~ 2018-11-02 10:48:47 JussiMozo   "Wor~ Twitt~
## 19 716125~ 10584646~ 2018-11-02 21:03:29 EzeAsukwu   @cho~ Twitt~
## 20 101369~ 10583682~ 2018-11-02 14:40:30 tomaszkoni~ "Prz~ Twitt~
## # ... with 82 more variables: display_text_width <dbl>,
## #   reply_to_status_id <chr>, reply_to_user_id <chr>,
## #   reply_to_screen_name <chr>, is_quote <lgl>, is_retweet <lgl>,
## #   favorite_count <int>, retweet_count <int>, hashtags <list>,
## #   symbols <list>, urls_url <list>, urls_t.co <list>,
## #   urls_expanded_url <list>, media_url <list>, media_t.co <list>,
## #   media_expanded_url <list>, media_type <list>, ext_media_url <list>,
## #   ext_media_t.co <list>, ext_media_expanded_url <list>,
## #   ext_media_type <chr>, mentions_user_id <list>,
## #   mentions_screen_name <list>, lang <chr>, quoted_status_id <chr>,
## #   quoted_text <chr>, quoted_created_at <dttm>, quoted_source <chr>,
## #   quoted_favorite_count <int>, quoted_retweet_count <int>,
## #   quoted_user_id <chr>, quoted_screen_name <chr>, quoted_name <chr>,
## #   quoted_followers_count <int>, quoted_friends_count <int>,
## #   quoted_statuses_count <int>, quoted_location <chr>,
## #   quoted_description <chr>, quoted_verified <lgl>,
## #   retweet_status_id <chr>, retweet_text <chr>,
## #   retweet_created_at <dttm>, retweet_source <chr>,
## #   retweet_favorite_count <int>, retweet_retweet_count <int>,
## #   retweet_user_id <chr>, retweet_screen_name <chr>, retweet_name <chr>,
## #   retweet_followers_count <int>, retweet_friends_count <int>,
## #   retweet_statuses_count <int>, retweet_location <chr>,
## #   retweet_description <chr>, retweet_verified <lgl>, place_url <chr>,
## #   place_name <chr>, place_full_name <chr>, place_type <chr>,
## #   country <chr>, country_code <chr>, geo_coords <list>,
## #   coords_coords <list>, bbox_coords <list>, status_url <chr>,
## #   name <chr>, location <chr>, description <chr>, url <chr>,
## #   protected <lgl>, followers_count <int>, friends_count <int>,
## #   listed_count <int>, statuses_count <int>, favourites_count <int>,
## #   account_created_at <dttm>, verified <lgl>, profile_url <chr>,
## #   profile_expanded_url <chr>, account_lang <chr>,
## #   profile_banner_url <chr>, profile_background_url <chr>,
## #   profile_image_url <chr>

Text Cleaning

library(tm)
## Loading required package: NLP
## 
## Attaching package: 'NLP'
## The following object is masked from 'package:ggplot2':
## 
##     annotate

Build corpus

# build a corpus, and specify the source to be character vectors 
myCorpus <- Corpus(VectorSource(tweets$text))
# convert to lower case
myCorpus <- tm_map(myCorpus, content_transformer(tolower))
## Warning in tm_map.SimpleCorpus(myCorpus, content_transformer(tolower)):
## transformation drops documents
# remove URLs
removeURL <- function(x) gsub("http[^[:space:]]*", "", x)
myCorpus <- tm_map(myCorpus, content_transformer(removeURL))
## Warning in tm_map.SimpleCorpus(myCorpus, content_transformer(removeURL)):
## transformation drops documents
# remove anything other than English letters or space 
removeNumPunct <- function(x) gsub("[^[:alpha:][:space:]]*", "", x) 
myCorpus <- tm_map(myCorpus, content_transformer(removeNumPunct))
## Warning in tm_map.SimpleCorpus(myCorpus,
## content_transformer(removeNumPunct)): transformation drops documents
# remove stopwords
myStopwords <- c(setdiff(stopwords('english'), c("r", "big")), "use", "see", "used", "via", "amp", "indihome")
stopwords_id <- read.table('E:/stopwords-id.txt', header = FALSE)
myStopwords <- c(myStopwords, as.matrix(stopwords_id$V1), "hi", "yg")
myCorpus <- tm_map(myCorpus, removeWords, myStopwords)
## Warning in tm_map.SimpleCorpus(myCorpus, removeWords, myStopwords):
## transformation drops documents
# remove extra whitespace
myCorpus <- tm_map(myCorpus, stripWhitespace)
## Warning in tm_map.SimpleCorpus(myCorpus, stripWhitespace): transformation
## drops documents
# keep a copy for stem completion later
myCorpusCopy <- myCorpus

Frequent Words

Build Term Document Matrix

tdm <- TermDocumentMatrix(myCorpus, control = list(wordLengths = c(1, Inf)))
tdm
## <<TermDocumentMatrix (terms: 502, documents: 52)>>
## Non-/sparse entries: 933/25171
## Sparsity           : 96%
## Maximal term length: 27
## Weighting          : term frequency (tf)

Top Frequent Terms

freq.terms <- findFreqTerms(tdm, lowfreq = 20)
freq.terms[1:50]
##  [1] "pkm" NA    NA    NA    NA    NA    NA    NA    NA    NA    NA   
## [12] NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA   
## [23] NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA   
## [34] NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA   
## [45] NA    NA    NA    NA    NA    NA
term.freq <- rowSums(as.matrix(tdm))
term.freq <- subset(term.freq, term.freq >= 10)
df <- data.frame(term = names(term.freq), freq = term.freq)
ggplot(df,aes(x=term, y=freq)) + geom_bar(stat="identity") +
  xlab("Terms") + ylab("Count") + coord_flip() +
  theme(axis.text=element_text(size=7))

Wordcloud

Build Wordcloud

library(wordcloud)
## Loading required package: RColorBrewer
m <- as.matrix(tdm)
# calculate the frequency of words and sort it by frequency 
word.freq <- sort(rowSums(m), decreasing = T)
# colors
pal <- brewer.pal(9, "BuGn")[-(1:4)]
wordcloud(words = names(word.freq), freq = word.freq, min.freq = 3,
    random.order = F, colors = pal)