[This article was first published on Rcrastinate
, and kindly contributed to R-bloggers
]. (You can report issue about the content on this page here
Want to share your content on R-bloggers? click here
if you have a blog, or here
if you don't.
There are a few reasons why you might want to send tweets from R. You might want to write a Twitter bot or – as in my case – you want to send yourself a tweet when a very long computation finishes.
So, here I will run you through all the steps you have to take using
– Twitter’s API and
– the twitteR package written by Jeff Gentry
The setup to send myself tweets is the following: I have my main twitter account and an additional account I am only using to tweet from R. I am following the additional account with my main account. On my phone’s Twitter app, my main account is logged in and notifications are activated only for the additional account. So, whenever I tweet something with the additional account, the new tweet pops up on my phone.
Let’s get started.
Step 1: Create an additional twitter account and log in with this one.
Step 2: Go to apps.twitter.com (Application Management) and create a new app. After completing the process your Application Management main screen should look something like this.
Step 3: Click on the name of your app and then select “manage keys and access tokens”. This should look like this (without the red boxes, of course).
Step 4: Copy your Consumer Key, Consumer Secret, Access Token and Access Token Secret. You will need them for authenticating from your R script.
Step 5: Fire up R and install the twitteR package.
setup_twitter_oauth(consumer_key = ““,
access_token = ““,
consumer_secret = ““,
access_secret = ““)
Step 6: Tweet something!
tw <- updateStatus("My first tweet from R!")
Basically, that’s it. But you can do more cool stuff. If, for example, you only want to read the notification about the tweet on your phone, you can delete the latest tweet just as fast.
Aaaand, it’s gone!
You can also include a plot you just did in R! In this case, do not delete the tweet, because the media file will be deleted too and you cannot view it. Let’s do this.
t1 <- Sys.time()
gauss <- rnorm(n = 10000)
t2 <- difftime(Sys.time(), t1, units = "secs")
tw <- updateStatus(paste("Finished in", round(t2, 2), "seconds"), mediaPath = "temp.jpg")
And just a few seconds later, this pops up on my phone.
I’m sure you’ll come up with a lot of more cool stuff you can do with that. Let’s hear them in the comments. Also, feel free to report any problems and I will try to help.