Reputation: 1944
There are several similar questions on SO to this but I can't find an exact match for what I'm looking for.
I'd like to set some vertex attributes for a list of graphs, using igraph's
set_vertex_attr
function. I'd like to have all variables in a split
data_frame
as the attributes and use the variable names as vertex attribute names. My approach is to use a loop within a loop, but this is too advanced for me and I've hit a roadblock. Here is my code:
library(tidyverse) #to keep it tidy
library(igraph) #for graphs
list_graphs <- list(graph.star(5),
graph.star(5),
graph.star(5))
df <- data_frame(name = c(rep('one',5),
rep('two',5),
rep('three',5)),
x_vary = sample(1:1000,15),
y_vary = sample(1:1000,15))
ls_dfs <- split(df,f= df$name)
for(i in seq_along(list_graphs)){
for(j in seq_along(ls_dfs)){
set_vertex_attr(graph = list_graphs[[i]],
name = names(df[i]),
value = ls_dfs[[i]][[j]])
}
}
The output I'm looking for is for each graph in list_graphs
to have the following vertex attribute names and attributes sourced from the data_frame
.
Upvotes: 0
Views: 84
Reputation: 206401
Seems like this might be what you need
map2(list_graphs, ls_dfs, function(g, attr) {vertex_attr(g)<- attr; g})
We use map2
from the tidyverse to walk over the list_graphs
and ls_dfs
together. This does assume that the sequence in each match up. Note that in your example you have names(ls_dfs ) == c("one", "three", "two")
which might not be the order you expect.
But then we just use vertex_attr<-
to set all the attributes at once by assigning the data.frame since a data.frame is really just a named list.
Upvotes: 1