[This article was first published on R snippets, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Last week I analyzed Shapley-Shubik power index in R. I got several requests to write a code calculating Banzhaf power index. Here is the proposed code.Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Again I use data from Warsaw School of Economics rector elections (the details are in my last post). I give the code for calculation of Shapley-Shubik and Banzhaf power indices below.
# Constituency list< o:p>
const <- c(30, 22, 27, 27, 41, 2 + 11, 38 + 5, 1 + 9)< o:p>
# Shapley-Shubik power index< o:p>
library(gtools)< o:p>
perms <- permutations(8, 8)< o:p>
outcome <- apply(perms, 1, function(x) {< o:p>
x[sum(cumsum(const[x]) < 107) + 1] })< o:p>
sspi <- prop.table(table(outcome))< o:p>
# Banzhaf power index< o:p>
subsets <- length(const) – 1< o:p>
subs <- matrix(FALSE, 2 ^ subsets, subsets)< o:p>
for (i in 1:subsets) {< o:p>
subs[,i] <- rep(c(rep(FALSE, 2 ^ (i – 1)),< o:p>
rep(TRUE, 2 ^ (i – 1))),< o:p>
2 ^ (subsets – i))< o:p>
}< o:p>
banzhaf <- function(i) {< o:p>
other <- const[-i]< o:p>
part.sum <- apply(subs, 1, function(x) { sum(other[x]) } )< o:p>
sum((part.sum < 106.5) & ((part.sum + const[i]) > 106.5))< o:p>
}< o:p>
bpi <- prop.table(sapply(1:8, banzhaf))< o:p>
# power index comparison< o:p>
names(bpi) <- c(“C_1”,“C_2”, “C_3”, “C_4”, “C_5”,< o:p>
“C_67”, “C_89”, “C_1011”)< o:p>
barplot(rbind(bpi, sspi, const / sum(const))[,order(const)],< o:p>
col=c(2,4,1), beside = TRUE,< o:p>
legend.text = c(“Banzhaf”, “Shapley-Shubik”, “Votes”),< o:p>
args.legend = list(x = “top”))< o:p>
Calculating Banzhaf power index is more complex to implement in R in comparison to Shapley-Shubik power index but the code is faster.
At the end of the code I plot comparison of both power indices. It is interesting to note that the results are very similar. Banzhaf power index slightly favors smaller constituencies but the difference is negligible. Again we can see that although constituency #2 has over 50% more votes than combined constituencies #6 and #7 (22 vs. 13) it has exactly the same power according to both indices.
To leave a comment for the author, please follow the link and comment on their blog: R snippets.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.