# Graphing Twitter friends/followers with R (updated)

June 24, 2010
By

(This article was first published on Cornelius Puschmann's Blog » R, and kindly contributed to R-bloggers)

Edit: And here is an update of the update, this one contributed by Kai Heinrich.

Here’s an updated version of my script from last month, something I’ve been meaning to do for a while. I thank Anatol Stefanowitsch and Gábor Csárdi for improving my quite sloppy code.

``` # Load twitteR and igraph packages. library(twitteR) library(igraph) ```
``` # Start a Twitter session. sess <- initSession('USERNAME', 'PASSWORD') ```
``` # Retrieve a maximum of 20 friends/followers for yourself or someone else Note that # at the moment, the limit parameter does not [yet] seem to be working. friends.object <- userFriends('USERNAME', n=20, sess) followers.object <- userFollowers('USERNAME', n=20, sess) ```
``` # Retrieve the names of your friends and followers from the friend # and follower objects. friends <- sapply(friends.object,name) followers <- sapply(followers.object,name) ```
``` # Create a data frame that relates friends and followers to you for expression in the graph relations <- merge(data.frame(User='YOUR_NAME', Follower=friends), data.frame(User=followers, Follower='YOUR_NAME'), all=T) ```
``` # Create graph from relations. g <- graph.data.frame(relations, directed = T) ```
``` # Assign labels to the graph (=people's names) V(g)\$label <- V(g)\$name ```
``` # Plot the graph using plot() or tkplot(). tkplot(g) ```

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...