This week in Data Without Borders we covered extrapolating data from time series events with R. Time series events are usually defined as a one dimensional value measured at different times. For instance, the value of a stock over the course of a month, or tweets with #WorldSeries over the past week.

The two major questions to investigate in time series are:

  1. Which events signal anomalies?
  2. Are there cycles (“seasonality”) present?

The code block below takes tweets mentioning Iran over the course of five days. The purpose of this assignment is to locate when there’s an unusually high velocity of tweets mentioning Iran, and investigate the text of those tweets, or better yet, why is Iran trending on Twitter?

In short, the tweets where there’s the largest velocity in number of tweets mentioning Iran are talking about the Iranian elections, and how both candidates are declaring victory.

# Import the data and TTR library:
#tweets = read.csv("http://jakeporway.com/teaching/data/tweets2009.csv", header=FALSE, as.is=TRUE)
tweets = read.csv("/Users/evanemolo/Dropbox/_ITP/_Fall_2012/DWB/HW/WK6/tweets2009.csv", as.is=TRUE, header=FALSE)
library(TTR)
# Assign a vector to the names() function to name the columns
names(tweets) = c("time", "seconds", "screen_name", "text")
# Let's search the tweets for "Iran" using grep()
iran.tweets = tweets[grep("iran", ignore.case=TRUE, tweets$text), ]
# Plot the time series for iran.tweets
iran.tweets.hist = hist(iran.tweets$seconds, breaks=100)
plot(iran.tweets.hist$counts, type='l')
# Mark the three largest peaks on the time series
abline(v=which(iran.tweets.hist$counts > 30), col=2)
# Set up the time series for SMA (moving average)
iran.tweets.ts = ts(iran.tweets.hist$counts, start=c(1244745260,1))
plot.ts(iran.tweets.ts)
iran.tweets.ts.sma = SMA(iran.tweets.ts)
plot.ts(iran.tweets.ts.sma)
# Build a basic event detection algorithm with the diff() function
# and a lag of 5
iran.tweets.diff = diff(iran.tweets.ts.sma, lag=5)
plot.ts(iran.tweets.diff)
# Show both the SMA graph and the diff graph
par(mfrow=c(2,1))
plot.ts(iran.tweets.ts.sma, type='l', main="Moving Average of Tweets")
plot.ts(iran.tweets.diff, type='l', main="diff")
# What do you see?
# The highest increase in tweet volume corresponds to the increase
# in the moving average of tweets
# Can we figure out what time the tweets started increasing using your
# results from diff?
# Pull 20 or so tweets from around that time and write down why you think
# they’re increasing based on what people are saying.
# Where is the spike on the diff chart?
which.max(iran.tweets.diff)
# row 38
# Now look at tweets near that peak
iran.tweets[38:58, "text"]
# People are talking about:
# Iranian election results are reported; both candidates claim victory...
view raw DWB-6.R hosted with ❤ by GitHub