I am trying to create an igraph
object splitting a string vector on a special character ("&").
I use a for-loop to create a vector and convert that into a network graph.
The code works but is extremely inefficient on very long vectors (large networks).
Is there a way to improve the process with pipes and mapping? Thanks in advance
require(graph)
data <- data.frame(nodes=c("A","A & B","C","B & C","B & D"))
V <- c()
for (i in 1:nrow(data)){
V_temp <- data[i,]
ifelse(grepl(" & ", data$nodes[i]),
N <- t(combn(unlist(strsplit(data$nodes[i], " & ")),2)),
N <- matrix(rep(data$nodes[i],2), nrow = 1, ncol = 2))
colnames(N) <- c("N1","N2")
V_temp <- cbind(N, V_temp, row.names = NULL)
V <- as.data.frame(rbind(V, V_temp, row.names = NULL))
}
vector <- rbind(as.vector(as.character(V$N1)),
as.vector(as.character(V$N2)))
plot(graph(vector, directed = FALSE))