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.

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

const **<-** c**(**30, 22, 27, 27, 41, 2 **+** 11, 38 **+** 5, 1 **+** 9**)**

# Shapley-Shubik power index

library**(**gtools**)**

perms **<-** permutations**(**8, 8**)**

outcome **<-** apply**(**perms, 1, **function****(**x**)** **{**

x**[**sum**(**cumsum**(**const**[**x**]) < **107**)** **+** 1**]** **})**

sspi **<-** prop.table**(**table**(**outcome**))**

# Banzhaf power index

subsets **<-** length**(**const**)** **–** 1

subs **<-** matrix**(****FALSE**, 2 **^ **subsets, subsets**)**

**for** **(**i **in** 1**:**subsets**)** **{**

subs**[**,i**]** **<-** rep**(**c**(**rep**(****FALSE**, 2 **^** **(**i **–** 1**))**,

rep**(****TRUE**, 2 **^** **(**i **–** 1**)))**,

2 **^** **(**subsets **–** i**))**

**}**

banzhaf **<-** **function****(**i**)** **{**

other **<-** const**[-**i**]**

part.sum **<-** apply**(**subs, 1, **function****(**x**)** **{** sum**(**other**[**x**])** **}** **)**

sum**((**part.sum **<** 106.5**)** **&** **((**part.sum **+** const**[**i**])** **>** 106.5**))**

**}**

bpi **<-** prop.table**(**sapply**(**1**:**8, banzhaf**))**

# power index comparison

names**(**bpi**)** **<-** c**(**“C_1″,“C_2″, “C_3″, “C_4″, “C_5″,

“C_67″, “C_89″, “C_1011″**)**

barplot**(**rbind**(**bpi, sspi, const **/** sum**(**const**))[**,order**(**const**)]**,

col**=**c**(**2,4,1**)**, beside **=** **TRUE**,

legend.text **=** c**(**“Banzhaf”, “Shapley-Shubik”, “Votes”**)**,

args.legend **= **list**(**x **= **“top”**))**

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.

*Related*

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 on topics such as: visualization (

ggplot2,

Boxplots,

maps,

animation), programming (

RStudio,

Sweave,

LaTeX,

SQL,

Eclipse,

git,

hadoop,

Web Scraping) statistics (

regression,

PCA,

time series,

trading) and more...

If you got this far, why not

__subscribe for updates__ from the site? Choose your flavor:

e-mail,

twitter,

RSS, or

facebook...