I am relatively new to R and I am have issues in creating an adjacency matrix using group characteristics.
I have a data frame that looks like this:
distid villageid hhid group1 group2 group3 group4
1 1 111 0 1 0 0
1 1 112 1 1 1 0
1 2 121 1 1 0 1
1 2 122 1 0 0 1
2 1 211 1 1 0 0
2 1 212 1 1 1 1
2 2 221 0 0 1 0
2 2 222 0 1 1 0
I need to create an adjacency matrix where if a hhid is in the same distid, villageid and group then they are all fully connected.
So my final matrix should look something like this
hhid 111 112 121 122 211 212 221 222
111 0 1 0 0 0 0 0 0
112 1 0 0 0 0 0 0 0
121 0 0 0 1 0 0 0 0
122 0 0 0 0 0 0 0 0
211 0 0 0 0 0 1 0 0
212 0 0 0 0 1 0 0 0
221 0 0 0 0 0 0 0 1
222 0 0 0 0 0 0 1 0
We assume that what is wanted is that two elements are regarded as adjacent if they are in the same group, dist and village.
Using the input in the Note create the adjacency matrices for groups, for distid and for villageid and then multiply them together and zero out the diagonal.
m1 <- sign(crossprod(t(DF[-(1:3)])))
m2 <- +outer(DF$distid, DF$distid, "==")
m3 <- +outer(DF$villageid, DF$villageid, "==")
m4 <- 1 - diag(nrow(DF))
m <- m1 * m2 * m3 * m4
dimnames(m) <- list(DF$hhid, DF$hhid)
giving:
> m
111 112 121 122 211 212 221 222
111 0 1 0 0 0 0 0 0
112 1 0 0 0 0 0 0 0
121 0 0 0 1 0 0 0 0
122 0 0 1 0 0 0 0 0
211 0 0 0 0 0 1 0 0
212 0 0 0 0 1 0 0 0
221 0 0 0 0 0 0 0 1
222 0 0 0 0 0 0 1 0
library(igraph)
g <- graph_from_adjacency_matrix(m)
plot(g)
The input in reproducible form.
Lines <- "distid villageid hhid group1 group2 group3 group4
1 1 111 0 1 0 0
1 1 112 1 1 1 0
1 2 121 1 1 0 1
1 2 122 1 0 0 1
2 1 211 1 1 0 0
2 1 212 1 1 1 1
2 2 221 0 0 1 0
2 2 222 0 1 1 0"
DF <- read.table(text = Lines, header = TRUE)