The as_data_frame(graph)
function usage returns a dataframe with from and to columns (vertices) as well as a weight for the edge.
The values in the from and to columns appear to be drawn from the $name
attribute. Is it possible to change which attribute is reported as values in these columns? for example $speciesname
?
Thanks.
This is not directly possible. However, you can get both the vertices and the edges as a dataframe, and then use standard R operations to get the appropriate information.
If you pass what="both"
you get both the vertices and edges as a dataframe: df <- as_data_frame(graph, what="both")
. Then df$vertices["speciesname"]
will give the desired attribute, with each row being labeled by the vertex name V(graph)$name
. Hence, you can simply add the columns (using dplyr
library) as follows
df$edges %>%
mutate(from_speciesname = df$vertices[.$from,"speciesname"],
to_speciesname = df$vertices[.$to,"speciesname"])
Yep thanks. I actually did something similar using tidyverse since my post. Posting below in case it may benefit others down the line.
# view the edges as a dataframe
y = as_data_frame(grph.pos, what = "edges")
# note the to and from is displayed as the stock names, which are digits instead of taxonomic classification. Not that informative off the bat.
# use as_data_frame with vertices to see the identity of each digit
x = as_data_frame(grph.pos, what = "vertices")
left_join(y, x %>% select(name,Taxspecies), by = c("from" = "name")) %>%
dplyr::rename("FROM" = Taxspecies) %>%
left_join(., x %>% select(name,Taxspecies), by = c("to" = "name")) %>%
dplyr::rename("TO" = Taxspecies) %>%
select(FROM, TO, weight)
1 Like