Skip to content

Instantly share code, notes, and snippets.

@alexbrey
Forked from mdlincoln/project.R
Last active August 10, 2016 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexbrey/f0c8fab0af797f10f46d368b601092f0 to your computer and use it in GitHub Desktop.
Save alexbrey/f0c8fab0af797f10f46d368b601092f0 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(artist2_id = artist_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", "date", "artist2_id"
# In order to load this into igraph, reorder the columns so with the source and target as the first two columns
edges <- edges[c("artist_id", "artist2_id", "object_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, 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