Skip to content

Instantly share code, notes, and snippets.

@mdlincoln
Last active August 10, 2016 01:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mdlincoln/84f10ca04ddb7d743d6c73a85c5027b3 to your computer and use it in GitHub Desktop.
Save mdlincoln/84f10ca04ddb7d743d6c73a85c5027b3 to your computer and use it in GitHub Desktop.
Maintain other attributes when making a bipartite projection
library(igraph)
library(dplyr)
# Assume you have a dataframe "objects" with columns "object_id", "artist_id", "date"
# Create an identical table that just gives a new variable name to "artist_id"
flipped_objects <- objects %>% rename(artist_id = artist2_id)
# Join the tables together (essentially joining objects to itself, creating every combination
# of artist that share an object_id and date
edges <- objects %>%
left_join(flipped_objects, by = c("object_id", "date")) %>%
filter(artist_id != artist2_id)
# The data.frame "edges" should now have the columns "object_id", "artist_id", "artist2_id", "date"
# You will still want to simplify the graph because every artist-artist relationship will
# effectively be doubled by the left_join. Simplifying here, with the appropriate value of
# edge.attr.comb, will preserve the date value when you simplify it.
object_graph <- simplify(graph_from_data_frame(edges = edges, directed = FALSE),
edge_attr_comb = list(object_id = "first", date = "first"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment