user3570187 - 9 months ago 74

R Question

Following up on my previous question, I would like to create degree centrality for with the following data.

I tried to replicate the previous example on stackoverflow (how to find degree centrality of nodes in a matrix?) but I had some challenges.

`a <- c('nancy','bill','bob','badri','bill','kiron','david')`

b <- c('martial-arts','dance','sports','judo','judo','judo','judo')

df <- data.frame(a, b)

From this data i need to create an adjacency matrix : (where u1, u2, u3, u4,u5,u6 represents nancy, bill,bob, badri users and how they are connected through the clubs they are participating in). Can someone help?

I am having difficulty in creating this adjacency matrix from raw data. Can someone suggest any ideas on how to proceed.

Answer

This solution comes via Solomon Messing:

```
M <- as.matrix(table(df))
M <- tcrossprod(M)
diag(M) <- 1
M
# a
# a badri bill bob david kiron nancy
# badri 1 1 0 1 1 0
# bill 1 1 0 1 1 0
# bob 0 0 1 0 0 0
# david 1 1 0 1 1 0
# kiron 1 1 0 1 1 0
# nancy 0 0 0 0 0 1
```

See the complete post for guidance on how to do this in a sparse matrix.

Source (Stackoverflow)