#Read Preference Data
htv <- read.csv("R/BendigoHtV.csv", header=T)
htv
##   Party NAT GRN RUA LAB LIB ANJ IND FAM
## 1   NAT   1   8   5   6   2   7   4   3
## 2   GRN   5   1   8   2   4   3   7   6
## 3   RUA   4   8   1   7   5   6   2   3
## 4   LAB   4   2   7   1   5   3   8   6
## 5   LIB   2   7   8   6   1   4   5   3
## 6   ANJ   7   2   8   3   4   1   5   6
## 7   IND   4   7   2   8   5   6   1   3
## 8   FAM   3   8   4   7   2   6   5   1
#Convert preferences to points matrix
#Second preference = 7 points
row.names(htv) <- htv[,1]
htv <- as.matrix(9-htv[,-1])

#Remove self-preference (first preference)
diag(htv) <- 0
htv
##     NAT GRN RUA LAB LIB ANJ IND FAM
## NAT   0   1   4   3   7   2   5   6
## GRN   4   0   1   7   5   6   2   3
## RUA   5   1   0   2   4   3   7   6
## LAB   5   7   2   0   4   6   1   3
## LIB   7   2   1   3   0   5   4   6
## ANJ   2   7   1   6   5   0   4   3
## IND   5   2   7   1   4   3   0   6
## FAM   6   1   5   2   7   3   4   0
#Number of points received by parties
#Each partie can distribute 28 points (1-7)
#Max=7*7, min=7*1
barplot(sort(colSums(htv)), ylim=c(7,49))
abline(h=7, col="red")
abline(h=49, col="red")

#Calculate net scores (strength of ties) between parties
htv[lower.tri(htv)] <- htv[lower.tri(htv)]+htv[upper.tri(htv)]
htv[upper.tri(htv)] <- 0
htv
##     NAT GRN RUA LAB LIB ANJ IND FAM
## NAT   0   0   0   0   0   0   0   0
## GRN   5   0   0   0   0   0   0   0
## RUA   9   6   0   0   0   0   0   0
## LAB   6  11   8   0   0   0   0   0
## LIB  10   6   6   4   0   0   0   0
## ANJ   9   9   6  10   8   0   0   0
## IND   7   8   9   5  10   9   0   0
## FAM  13   4  12   8  10   6  10   0
#Network analysis
#Spinglass community detection based on the strength of ties
library(igraph)
## 
## Attaching package: 'igraph'
## The following objects are masked from 'package:stats':
## 
##     decompose, spectrum
## The following object is masked from 'package:base':
## 
##     union
g <- graph.adjacency(htv, weighted=T, mode = "undirected")
c <- spinglass.community(g)
plot(c,g)