Install new libraries

install.packages("networkD3") #for interactive network visualization
install.packages("igraph") #for network analysis

Load required libraries

library(twitteR)
library(dplyr)
library(qdap)
library(networkD3)
library(igraph)
library(stringr) 

Collect tweets through Twitter API

setup_twitter_oauth("enter consumer key", 
                    "enter consumer secret", 
                    access_token="xxxxx", 
                    access_secret="xxxx")

#collect recent 5000 tweets
alltweets <- twListToDF(searchTwitter("#MAGA", n=5000, lang=NULL,since=NULL, until=NULL,locale=NULL, geocode=NULL, sinceID=NULL, maxID=NULL,resultType=NULL, retryOnRateLimit=120))

#save tweets as .csv
write.csv(alltweets, "alltweets.csv")

Alternatively, you can use pre-saved data

alltweets <- read.csv("alltweets.csv", header = TRUE)

Extract network information from retweets. If A retweets B, then there is a link from A to B.

#Network analysis and visualization is computationally intensive. We will use only the first 500 tweets for demo.

alltweets<-alltweets[1:500,]

#split the data into two sets; one for retweet network and the other for mention network.

#create an edge-list for retweet network
sp = split(alltweets, alltweets$isRetweet)
rt = mutate(sp[['TRUE']], sender = substr(text, 5, regexpr(':', text) - 1))
el = as.data.frame(cbind(sender = tolower(rt$sender), receiver = tolower(rt$screenName)))
el = count(el, sender, receiver) 
el[1:5,] #show the first 5 edges in the edgelist

Based on the edge-list, create a retweet network.

rt_graph <- graph_from_data_frame(d=el, directed=T)

Visualize the retweet network.

glay = layout.fruchterman.reingold(rt_graph) 
plot(rt_graph)