Text Analysis of Trump's Tweets Confirms He Writes Only the (Angrier) Android Half
Using R (particularly the twitteR package) author David Robinson tests the theory that the tone of Donald Trump's tweets depends on which device it was typed on.
Join the DZone community and get the full member experience.Join For Free
i don’t normally post about politics (i’m not particularly savvy about polling, which is where data science has had the largest impact on politics ), but this weekend i saw a hypothesis about donald trump’s twitter account that simply begged to be investigated with data:
when trump wishes the olympic team good luck, he’s tweeting from his iphone. when he’s insulting a rival, he’s usually tweeting from an android. is this an artifact showing which tweets are trump’s own and which are by some handler?
others have explored trump’s timeline and noticed this tends to hold up—and trump himself does indeed tweet from a samsung galaxy . but, how could we examine it quantitatively? i’ve been writing about text mining and sentiment analysis recently, particularly during my development of the tidytext r package with julia silge, and this is a great opportunity to apply it again.
my analysis, shown below, concludes that the android and iphone tweets are clearly from different people , posting during different times of day and using hashtags, links, and retweets in distinct ways. what’s more, we can see that the android tweets are angrier and more negative , while the iphone tweets tend to be benign announcements and pictures. overall, i’d agree with @tvaziri ’s analysis: this lets us tell the difference between the campaign’s tweets (iphone) and trump’s own (android).
first, we’ll retrieve the content of donald trump’s timeline using the
function in the
library(dplyr) library(purrr) library(twitter)
# you'd need to set global options with an authenticated app setup_twitter_oauth(getoption("twitter_consumer_key"), getoption("twitter_consumer_secret"), getoption("twitter_access_token"), getoption("twitter_access_token_secret")) # we can request only 3200 tweets at a time; it will return fewer # depending on the api trump_tweets <- usertimeline("realdonaldtrump", n = 3200) trump_tweets_df <- tbl_df(map_df(trump_tweets, as.data.frame))
# if you want to follow along without setting up twitter authentication, # just use my dataset: load(url("http://varianceexplained.org/files/trump_tweets_df.rda"))
we clean this data a bit, extracting the source application. (we’re looking only at the iphone and android tweets—a much smaller number are from the web client or ipad.)
library(tidyr) tweets <- trump_tweets_df %>% select(id, statussource, text, created) %>% extract(statussource, "source", "twitter for (.*?)<") %>% filter(source %in% c("iphone", "android"))
overall, this includes 628 tweets from iphone and 762 tweets from android.
one consideration is what time of day the tweets occur, which we’d expect to be a "signature" of their user. here we can certainly spot a difference:
library(lubridate) library(scales) tweets %>% count(source, hour = hour(with_tz(created, "est"))) %>% mutate(percent = n / sum(n)) %>% ggplot(aes(hour, percent, color = source)) + geom_line() + scale_y_continuous(labels = percent_format()) + labs(x = "hour of day (est)", y = "% of tweets", color = "")
trump on the android does a lot more tweeting in the morning, while the campaign posts from the iphone more in the afternoon and early evening.
another place we can spot a difference is in trump’s anachronistic behavior of "manually retweeting" people by copy-pasting their tweets, then surrounding them with quotation marks:
almost all of these quoted tweets are posted from the android:
in the remaining by-word analyses in this text, i’ll filter these quoted tweets out (since they contain text from followers that may not be representative of trump’s own tweets).
somewhere else we can see a difference involves sharing links or pictures in tweets.
tweet_picture_counts <- tweets %>% filter(!str_detect(text, '^"')) %>% count(source, picture = ifelse(str_detect(text, "t.co"), "picture/link", "no picture/link")) ggplot(tweet_picture_counts, aes(source, n, fill = picture)) + geom_bar(stat = "identity", position = "dodge") + labs(x = "", y = "number of tweets", fill = "")
it turns out tweets from the iphone were 38 times as likely to contain either a picture or a link. this also makes sense with our narrative: the iphone (presumably run by the campaign) tends to write "announcement" tweets about events, like this:
while android (trump himself) tends to write picture-less tweets like:
comparison of words
now that we’re sure there’s a difference between these two accounts, what can we say about the difference in the content ? we’ll use the tidytext package that julia silge and i developed.
we start by dividing into individual words using the
for more), and removing some common "stopwords":
library(tidytext) reg <- "([^a-za-z\\d#@']|'(?![a-za-z\\d#@]))" tweet_words <- tweets %>% filter(!str_detect(text, '^"')) %>% mutate(text = str_replace_all(text, "https://t.co/[a-za-z\\d]+|&", "")) %>% unnest_tokens(word, text, token = "regex", pattern = reg) %>% filter(!word %in% stop_words$word, str_detect(word, "[a-z]")) tweet_words
## # a tibble: 8,753 x 4 ## id source created word ## <chr> <chr> <time> <chr> ## 1 676494179216805888 iphone 2015-12-14 20:09:15 record ## 2 676494179216805888 iphone 2015-12-14 20:09:15 health ## 3 676494179216805888 iphone 2015-12-14 20:09:15 #makeamericagreatagain ## 4 676494179216805888 iphone 2015-12-14 20:09:15 #trump2016 ## 5 676509769562251264 iphone 2015-12-14 21:11:12 accolade ## 6 676509769562251264 iphone 2015-12-14 21:11:12 @trumpgolf ## 7 676509769562251264 iphone 2015-12-14 21:11:12 highly ## 8 676509769562251264 iphone 2015-12-14 21:11:12 respected ## 9 676509769562251264 iphone 2015-12-14 21:11:12 golf ## 10 676509769562251264 iphone 2015-12-14 21:11:12 odyssey ## # ... with 8,743 more rows
what were the most common words in trump’s tweets overall?
these should look familiar to anyone who has seen the feed. now, let’s consider which words are most common from the android relative to the iphone, and vice versa. we’ll use the simple measure of log odds ratio, calculated for each word as:
android_iphone_ratios <- tweet_words %>% count(word, source) %>% filter(sum(n) >= 5) %>% spread(source, n, fill = 0) %>% ungroup() %>% mutate_each(funs((. + 1) / sum(. + 1)), -word) %>% mutate(logratio = log2(android / iphone)) %>% arrange(desc(logratio))
which are the words most likely to be from android and most likely from iphone?
a few observations:
- most hashtags come from the iphone . indeed, almost no tweets from trump’s android contained hashtags, with some rare exceptions like this one . (this is true only because we filtered out the quoted "retweets", as trump does sometimes quote tweets like this that contain hashtags).
- words like "join" and "tomorrow", and times like "7pm", also came only from the iphone . the iphone is clearly responsible for event announcements like this one ("join me in houston, texas tomorrow night at 7pm!")
- a lot of "emotionally charged" words, like "badly", "crazy", "weak", and "dumb", were overwhelmingly more common on android. this supports the original hypothesis that this is the "angrier" or more hyperbolic account.
sentiment analysis: trump's tweets are much more negative than his campaign's
since we’ve observed a difference in sentiment between the android and iphone tweets, let’s try quantifying it. we’ll work with the nrc word-emotion association lexicon, available from the tidytext package, which associates words with 10 sentiments: positive , negative , anger , anticipation , disgust , fear , joy , sadness , surprise , and trust .
nrc <- sentiments %>% filter(lexicon == "nrc") %>% dplyr::select(word, sentiment) nrc
## # a tibble: 13,901 x 2 ## word sentiment ## <chr> <chr> ## 1 abacus trust ## 2 abandon fear ## 3 abandon negative ## 4 abandon sadness ## 5 abandoned anger ## 6 abandoned fear ## 7 abandoned negative ## 8 abandoned sadness ## 9 abandonment anger ## 10 abandonment fear ## # ... with 13,891 more rows
to measure the sentiment of the android and iphone tweets, we can count the number of words in each category:
sources <- tweet_words %>% group_by(source) %>% mutate(total_words = n()) %>% ungroup() %>% distinct(id, source, total_words) by_source_sentiment <- tweet_words %>% inner_join(nrc, by = "word") %>% count(sentiment, id) %>% ungroup() %>% complete(sentiment, id, fill = list(n = 0)) %>% inner_join(sources) %>% group_by(source, sentiment, total_words) %>% summarize(words = sum(n)) %>% ungroup() head(by_source_sentiment)
## # a tibble: 6 x 4 ## source sentiment total_words words ## <chr> <chr> <int> <dbl> ## 1 android anger 4901 321 ## 2 android anticipation 4901 256 ## 3 android disgust 4901 207 ## 4 android fear 4901 268 ## 5 android joy 4901 199 ## 6 android negative 4901 560
(for example, we see that 321 of the 4901 words in the android tweets were associated with "anger"). we then want to measure how much more likely the android account is to use an emotionally-charged term relative to the iphone account. since this is count data, we can use a poisson test to measure the difference:
library(broom) sentiment_differences <- by_source_sentiment %>% group_by(sentiment) %>% do(tidy(poisson.test(.$words, .$total_words))) sentiment_differences
## source: local data frame [10 x 9] ## groups: sentiment  ## ## sentiment estimate statistic p.value parameter conf.low ## <chr> <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 anger 1.492863 321 2.193242e-05 274.3619 1.2353162 ## 2 anticipation 1.169804 256 1.191668e-01 239.6467 0.9604950 ## 3 disgust 1.677259 207 1.777434e-05 170.2164 1.3116238 ## 4 fear 1.560280 268 1.886129e-05 225.6487 1.2640494 ## 5 joy 1.002605 199 1.000000e+00 198.7724 0.8089357 ## 6 negative 1.692841 560 7.094486e-13 459.1363 1.4586926 ## 7 positive 1.058760 555 3.820571e-01 541.4449 0.9303732 ## 8 sadness 1.620044 303 1.150493e-06 251.9650 1.3260252 ## 9 surprise 1.167925 159 2.174483e-01 148.9393 0.9083517 ## 10 trust 1.128482 369 1.471929e-01 350.5114 0.9597478 ## # ... with 3 more variables: conf.high <dbl>, method <fctr>, ## # alternative <fctr>
and we can visualize it with a 95% confidence interval:
thus, trump’s android account uses about 40-80% more words related to disgust , sadness , fear , anger , and other "negative" sentiments than the iphone account does. (the positive emotions weren’t different to a statistically significant extent.)
we’re especially interested in which words drove this different in sentiment. let’s consider the words with the largest changes within each category:
this confirms that lots of words annotated as negative sentiments (with a few exceptions like "crime" and "terrorist") are more common in trump’s android tweets than the campaign’s iphone tweets.
conclusion: the ghost in the political machine
i was fascinated by the recent new yorker article about tony schwartz, trump’s ghostwriter for the art of the deal. of particular interest was how schwartz imitated trump’s voice and philosophy:
in his journal, schwartz describes the process of trying to make trump’s voice palatable in the book. it was kind of "a trick," he writes, to mimic trump’s blunt, staccato, no-apologies delivery while making him seem almost boyishly appealing…. looking back at the text now, schwartz says, "i created a character far more winning than trump actually is."
like any journalism, data journalism is ultimately about human interest, and there’s one human i’m interested in: who is writing these iphone tweets?
the majority of the tweets from the iphone are fairly benign declarations. but consider cases like these, both posted from an iphone:
these tweets certainly sound like the trump we all know. maybe our above analysis isn’t complete:—maybe trump has sometimes, however rarely, tweeted from an iphone (perhaps dictating, or just using it when his own battery ran out). but what if our hypothesis is right, and these weren’t authored by the candidate—just someone trying their best to sound like him?
or what about tweets like this (also iphone), which defend trump’s slogan—but don’t really sound like something he’d write?
a lot has been written about trump’s mental state. but i’d really rather get inside the head of this anonymous staffer, whose job is to imitate trump’s unique cadence ("very sad!"), or to put a positive spin on it, to millions of followers. is he a true believer, or just a cog in a political machine, mixing whatever mainstream appeal he can into the @realdonaldtrump concoction? like tony schwartz, will he one day regret his involvement?
Published at DZone with permission of David Robinson, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.