Create an adjacency matrix of three variables with dplyr in R

Viewed 132

I am picking my eyes out to figure this out on Friday night. My data looks like this

df <- data.frame(teamA=c("Italy","Italy","England","England"),
                 teamB=c("Germany","Greece","Germany","Greece"), win=c(0,1,1,1))
df
    teamA   teamB win
1   Italy Germany   0
2   Italy  Greece   1
3 England Germany   1
4 England  Greece   1

and I want transform it to a matrix that look like this. Preferably with dplyr but I am so desperate that does not matter

         Italy   England 
Germany  0         1

Greece   1         1

3 Answers

Try with xtabs from base R and set the attributes to NULL (No packages needed)

out <- xtabs(win ~ teamB + teamA, df)
names(dimnames(out)) <- NULL

An option with igraph

graph_from_data_frame(df) %>%
    set_vertex_attr(name = "type", value = names(V(.)) %in% df$teamA) %>%
    as_incidence_matrix(attr = "win")

gives

        Italy England
Germany     0       1
Greece      1       1

Using pivot_wider -

library(tidyverse)

df %>%
  pivot_wider(names_from = teamA, values_from = win) %>%
  column_to_rownames('teamB') %>%
  as.matrix

#.       Italy England
#Germany     0       1
#Greece      1       1
Related