Reputation: 5935
I am working with the R programming language.
I have the following data set (route_1):
route_1
id long lat
1 1 -74.56048 40.07051
3 3 -72.44129 41.71506
4 4 -77.53908 41.55434
2 2 -74.23018 40.12929
6 6 -78.68685 42.35981
5 5 -79.26506 43.22408
Based on this data, I want to make a directed network graph in which each row is only linked to the row that comes right after. Using the "igraph" library, I was able to do this manually:
library(igraph)
my_data <- data.frame(
"node_a" = c("1", "3", "4", "2", "6"),
"node_b" = c("3", "4", "2", "6", "5")
)
graph <- graph.data.frame(my_data, directed=TRUE)
graph <- simplify(graph)
plot(graph)
My Question: Is it possible to make this above network graph directly using the "route_1" dataset, and without manually creating a new data set that contains information on which node is connected to what node?
Thanks!
Upvotes: 0
Views: 44
Reputation: 12165
Is the dataset always going to be ordered correctly, so the plot will go from row 1->2->3 etc in a single line? If so, we can make the node info dataframe by simply subsetting the ID column. If we put the steps in a function, it becomes a simple 1-liner:
plot_nodes <- function(x) {
id = x$id
a = id[1:length(id)-1]
b = id[2:length(id)]
graph.data.frame(data.frame(a,b), directed=TRUE)
}
graph <- plot_nodes(route_1)
plot(simplify(graph))
Upvotes: 1