rm(list=ls(all=TRUE)) getwd() setwd("C:/Users/mw/Dropbox (VOICES)/TOPIC MODEL") getwd() library(rtweet) library(ggmap) library(ggplot2) library(dplyr) library(readtext) library(quanteda) library(httpuv) library(maps) library(leaflet) library(dplyr) # Returns Twitter statuses matching a user provided search query. # ONLY RETURNS DATA FROM THE PAST 6-9 DAYS # Search for up to 100 (non-retweeted) tweets written in English containing the rstats hashtag without retweets. # Such query ONLY RETURNS DATA FROM THE PAST 6-9 DAYS rt <- search_tweets( "#rstats", n = 100, lang = "en", include_rts = FALSE) length(rt$text) # days covered by our analysis since <- rt$created_at[100] latest <- rt$created_at[1] cat("Twitter data","\n",paste("From:",since),"\n",paste(" To:",latest)) # print tweet text print(rt$text[1:5]) # lots of info about each single tweet colnames(rt) # Query to be searched must be a character string not to exceed maximum of 500 characters. # Spaces behave like boolean "AND" operator. To search for tweets containing at least one of multiple possible terms, # separate each search term with spaces and "OR" (in caps). # For example, the search q = "data science" looks for tweets containing both "data" and "science" # anywhere located anywhere in the tweets and in any order. # When "OR" is entered between search terms, query = "data OR science", Twitter should return any tweet that contains # either "data" or "science." # It is also possible to search for exact phrases using double quotes. # To do this, either wrap single quotes around a search query using double quotes, e.g., q = '"data science"' # or escape each internal double quote with a single backslash, e.g., q = "\"data science\"". # you can then save your results as a csv file write_as_csv(rt, "twitter.csv", prepend_ids = TRUE, na = "", fileEncoding = "UTF-8") ## plot time series of tweets ts_plot(rt, "1 hours") + theme_minimal() + theme(plot.title = element_text(face = "bold")) + labs( x = NULL, y = NULL, title = "Frequency of #rstats Twitter statuses from past 6-9 days", subtitle = "Twitter status (tweet) counts aggregated using one-hour intervals", caption = "Source: Data collected from Twitter's REST API via rtweet" ) ## plot time series of tweets frequency ts_plot(rt, by = "mins") ts_plot(rt, by = "days") # Next, let’s figure out who is tweeting about R using the #rstats hashtag. # you can access to users data discussing about #rstats via users_data() users_data(rt) # view column with screen names head(rt$screen_name) # get a list of unique usernames unique(rt$screen_name) # You can similarly use the search_users() function to just see what users are tweeting using a particular hashtag. # This function returns just a data.frame of the users and information about their accounts. # what users are tweeting with #rstats (max=100) users <- search_users("#rstats", n = 100) # once again, you can then save your results as a csv file write_as_csv(users, "users.csv", prepend_ids = TRUE, na = "", fileEncoding = "UTF-8") # What's the difference with search_tweets? That with search_tweets you retrieve a given amount of tweets, # with search_users you retrieve a given amount of UNIQUE users. If a user can tweets a lot about #rstats # it will count as "1 author" when using search_users, but his/her tweets will appear several times # in the data.frame you get out of search_tweets. And indeed compare the two above results: length(unique(users$user_id)) length(unique(rt$user_id)) # Let’s learn a bit more about these people tweeting about R. First, where are they from? # how many languages are represented (und=undeterminated) length(unique(users$lang)) count(users, lang, sort = TRUE) # how many locations are represented length(unique(users$location)) count(users, location, sort = TRUE) # Let’s sort by count and just plot the top locations. To do this you use top_n(). # Note that in this case you are grouping your data by user. count <- count(users, location, sort = TRUE) str(count) count <- count [-which(count$location == ""), ] str(count) count <- mutate(count, location = reorder(location, n)) count <- top_n(count, 20) ggplot(count, aes(x = location, y = n)) + geom_col() + coord_flip() + labs(x = "Count", y = "Location", title = "Where Twitter users are from - unique locations ") # Twitter rate limits cap the number of search results returned to 18,000 every 15 minutes. # To request more than that, simply set retryonratelimit = TRUE and rtweet will wait for rate limit resets for you. ## search for 20000 tweets containing the word data (do not run it!) ## rt <- search_tweets("data", n = 20000, retryonratelimit = TRUE) ## search for tweets containing "rstats", including retweets rtR <- search_tweets("rstats", n = 100) ## plot multiple time series--retweets vs non-retweets ts_plot(group_by(rtR, is_retweet), "hours") ## Get friends # Retrieve a list of all the accounts a user follows. ## get user IDs of accounts followed by CNN cnn_fds <- get_friends("cnn") str(cnn_fds) length(cnn_fds$user_id) ## lookup data on those accounts cnn_fds_data <- lookup_users(cnn_fds$user_id) head(cnn_fds_data$name) # Get followers # Retrieve a list of the accounts following a user ## get user IDs of accounts following CNN (just the first 100 in this example) cnn_flw <- get_followers("cnn", n = 100) ## lookup data on those accounts cnn_flw_data <- lookup_users(cnn_flw$user_id) head(cnn_flw_data$name) # Or if you really want ALL of their followers: ## how many followers does Curini have? curini_flw <- get_followers("Curini", retryonratelimit = TRUE) length(curini_flw$user_id) Curini <- lookup_users(curini_flw$user_id) head(Curini$name) # Get favorites # Get the 50 most recently favorited statuses by Curini. fav <- get_favorites("Curini", n = 50) print(fav$text[1:20]) print(fav$lang[1:20]) #Get trends # Discover what’s currently trending in San Francisco. sf <- get_trends("san francisco") sf$trend # Get timelines # Get the most recent 200 tweets from some important US political figures tmls <- get_timeline( c("ewarren", "BernieSanders", "realDonaldTrump"), n = 200 ) table(tmls$name) ## group by screen name and plot each time series [same two variants!] ts_plot(group_by(tmls, screen_name), "days") ######################################################################################### # geographical analysis: you need to have you google map API (but not if you are analyzing data from US only)! ######################################################################################### library(rtweet) api <- "YOUR GOOGLE MAP API" lookup_coords("usa") lookup_coords("london", apikey=api) lookup_coords("brazil", apikey=api) # What twitter will allow is for searches by geocode, and to achieve this, twitter will first check if the tweet is geocoded, # and if not, will check whether a place can be extrapolated from the user's profile information. So you could, for example, # search for tweets from the Barcelona area and twitter will deliver a lot of tweets that aren't geocoded because the users # have "Barcelona" in their profile. ## search for 1000 tweets sent from the US discussing about dinner or food rt <- search_tweets( "dinner OR food", n = 1000, geocode = lookup_coords("usa")) ## create lat/lng variables using all available tweet and profile geo-location data rtll <- lat_lng(rt) ## plot state boundaries par(mar = c(0, 0, 0, 0)) map("state", lwd = .25) ## plot lat and lng points onto state map with(rtll, points(lng, lat, pch = 20, cex = 5, col = rgb(0, .3, .7, .75))) # alternative plot via leaflet m2 <- leaflet(rtll) m2 <- addTiles(m2) # Add default OpenStreetMap map tiles m2 <- addMarkers(m2, lng=rtll$lng, lat=rtll$lat, popup=rtll$text) m2 ######################################################################################### # STREAMING data ######################################################################################### # with stream_tweets you capture via streaming the tweets opening a connection to the Streaming API that will return # all tweets that contain one or more of the keywords given in the track argument # There are four possible methods. (1) The default, q = "", returns a small random sample of all publicly available Twitter statuses # (1% random sample of all the tweets posted in that specific moment) # (2) To filter by keyword, provide a comma separated character string with the desired phrase(s) and keyword(s) # in this case it returns ALL the tweets, UNLESS that number of tweets is higher than 1% of *all* tweets # in a given moment # (3) Track users by providing a comma separated list of user IDs or screen names # (4) Use four latitude/longitude bounding box points to stream by geo location. This must be provided via a vector of length 4, e.g., c(-125, 26, -65, 49). # how to do that? check here! # http://boundingbox.klokantech.com/ and select "csv" dt <- stream_tweets("trump", timeout = 30) print(dt$text[1:10]) # I'd like to stream tweets from US (you do not need a GOOGLE MAP KEY to have these info - just for the US!) lookup_coords("USA") usa <- stream_tweets( c(122.85547, 20.35853, 154.00315, 45.64126 ), timeout = 30 ) # I'd like to stream tweets from Japan lookup_coords("Japan", apikey=api) ## use lookup_coords() for a shortcut verson of the above code [do not run] # japan <- stream_tweets(lookup_coords("Japan", apikey=api),timeout = 30) # print(japan $text[1:10]) ## or use the coordinates you get via lookup_coords japan2 <- stream_tweets( c(122.85547, 20.35853, 154.00315, 45.64126), timeout = 30 ) print(japan2 $text[1:10]) ## create lat/lng variables using all available tweet and profile geo-location data rtll_jp <- lat_lng(japan2 ) ## plot state boundaries par(mar = c(0, 0, 0, 0)) map("world", "Japan", lwd = .25) ## plot lat and lng points onto state map with(rtll_jp, points(lng, lat, pch = 20, cex = 5, col = rgb(0, .3, .7, .75))) # plot the results map.data <- map_data("world", "Japan") str(map.data) points <- data.frame(x = rtll_jp$lng, y = rtll_jp$lat ) ggplot(map.data) + geom_map(aes(map_id = region), map = map.data, fill = "white", color = "grey20", size = 0.25) + expand_limits(x = map.data$long, y = map.data$lat) + theme(axis.line = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), axis.title = element_blank(), plot.margin = unit(0 * c(-1.5, -1.5, -1.5, -1.5), "lines")) + geom_point(data = points, aes(x = x, y = y), size = 3, alpha = 1/3, color = "darkblue") # alternative plot via leaflet m2 <- leaflet(rtll_jp) m2 <- addTiles(m2) # Add default OpenStreetMap map tiles m2 <- addMarkers(m2, lng=rtll_jp$lng, lat=rtll_jp$lat, popup=rtll_jp$text) m2 # getting tweets from London rtl <- stream_tweets(lookup_coords("london", apikey=api), timeout = 20) length(rtl$text) str(rtl) ######################### ## Passing your rtweet results to Quanteda ######################### rt <- search_tweets("#rstats", n = 100, include_rts = FALSE, lang = "en") print(rt$lang[1:20]) colnames(rt) # I want to convert the POSIXct time format to a date (here you can also change the time zone by selecting tz="Hongkong" for example) # here I choose Greenwich Mean Time (GMT) str(rt$created_at) rt$date <- as.Date(rt$created_at, "GMT") str(rt$date) myCorpusTwitter<- corpus(rt) texts(myCorpusTwitter)[1:2] # number of documents ndoc(myCorpusTwitter) # inspect the document-level variables head(docvars(myCorpusTwitter)) # the remove_twitter = TRUE implies that when I do a dfm I remove Twitter characters @ and # myDfm <- dfm(myCorpusTwitter , remove = stopwords("english"), remove_punct = TRUE, remove_numbers=TRUE, tolower = TRUE, stem = TRUE, remove_twitter = TRUE, remove_url = TRUE) topfeatures(myDfm , 20) # 20 top words # Let me see my document-feature matrix for the first four documents and first 10 words myDfm[1:4, 1:10]