Home > Software engineering >  How can I add a numeric variable as "weights" for a Weighted Incidence Matrix in R?
How can I add a numeric variable as "weights" for a Weighted Incidence Matrix in R?

Time:11-24

I'd like to plot a weighted network with graph_from_incidence_matrix from the igraph package in R.

What I have (e.g.):

    episodes <- data.frame(
    director = c("name1","name1","name1", "name1", "name2","name3", "name3"), 
    writer = c("name4", "name5", "name4", "name6", "name6", "name7", "name4"), 
    rating = c(7.5,8.5,7,9,9,6,9))
    
    episodes

Basically, I'd like the network plot to show who collaborated with who (director-writer) and the connection "weight" to depict the rating #.

I'm not sure how to create the proper matrix for this. I've managed to create a sort of contingency table but with this I only get the collaborations and # of collabs (see below), I would like for these values to depict the ratings instead (or if there's any other way to "add" these "weights" to the network plot).

    #what I have so far:
    episodes2 <- table(episodes$director, episodes$writer)
    
    episodes2

Does this make sense or am I mixing things?

Thanks for any help!

CodePudding user response:

Try xtabs

> as.matrix(xtabs(rating ~ ., episodes))
        writer
director name4 name5 name6 name7
   name1  14.5   8.5   9.0   0.0
   name2   0.0   0.0   9.0   0.0
   name3   9.0   0.0   0.0   6.0

If you want to use igraph

episodes %>%
  graph_from_data_frame(directed = FALSE) %>%
  set_vertex_attr(name = "type", value = names(V(.)) %in% episodes$director) %>%
  simplify(edge.attr.comb = "sum") %>%
  as_incidence_matrix(attr = "rating")

which gives

      name1 name2 name3
name4  14.5     0     9
name5   8.5     0     0
name6   9.0     9     0
name7   0.0     0     6
  • Related