Skip to content

Instantly share code, notes, and snippets.

@katerinabc
Created June 21, 2018 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katerinabc/9925455b34a7ba34b261886eac8644f1 to your computer and use it in GitHub Desktop.
Save katerinabc/9925455b34a7ba34b261886eac8644f1 to your computer and use it in GitHub Desktop.
# create reply network
# To create a reply network we need to know the username, and to whom the replies were directed. The username we know, and the information about the replies is stored in the field `replyToSN`
reply_net <- data.frame(sender = "@katerinabohlec",
#receiver = userTl.df[,as.factor(4)] %>% group_by_(as.factor(replyToSN)) %>% summarize(weight = n()),
receiver=userTl.df[,c(4)],
type = "reply")
reply_net <- reply_net[-which(is.na(reply_net[,2])),]
dim(reply_net)
reply_net <- data.frame(sender = "@katerinabohlec",
reply_net %>% group_by(receiver) %>% summarize(weight = n()))
reply_net$type <- "reply"
# create mention network
mentioned =
lapply(userTl.df$text, function(tx) {
matches = gregexpr('@[^([:blank:]|[:punct:])]+', tx)[[1]]
sapply(seq_along(matches), function(i)
substr(tx, matches[i] + 1, matches[i] + attr(matches, 'match.length')[i] - 1))
})
mention_net =
lapply(seq_along(userTl.df$text), function(i) {
if(mentioned[[i]] == '')
return(NULL)
lapply(mentioned[[i]], function(m)
c(sender = as.character(userTl.df$screenName[i]), receiver = m)) %>%
do.call(rbind, .) %>% as.data.frame()
}) %>%
do.call(rbind, .) %>%
count(tolower(sender), tolower(receiver))
mention_net$type = "mentioned"
names(mention_net) <- c("sender", "receiver", "weight", "type")
tw_net <- rbind(reply_net, mention_net)
tw_net_g <- igraph::graph.data.frame(tw_net, directed=T)
# I'n going assume that the networks are very big. Visualizing them will be better in gephi
library(rgexf)
g1.gexf <- igraph.to.gexf(tw_net_g)
# You have to create a file connection.
f <- file("twitter_network.gexf")
writeLines(g1.gexf$graph, con = f)
close(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment