Home > Software design >  Creating a loop to utilise it in R package GameTheory
Creating a loop to utilise it in R package GameTheory

Time:01-28

I'm using R package GameTheory to calculate Shapley-Shubik power indices. The command itself is very simple, ShapleyShubik(quota, y, Names = NULL)

where quota is the minimum amount of votes to pass a vote, y seats of each party (number of) and Names are labels for the parties. It is simple to use 'manually', but I would like extend my usage to automate it to iterate through a vast amount of data that is compiled in an dataframe DF.

My dataframe DF includes four columns: AREA, PARTY LABEL, PARTYSEATS and MAJORITY:

AREA      PARTY LABEL    PARTYSEATS       MAJORITY
Area 1       A               5                5
Area 1       B               2                5
Area 1       C               1                5
Area 2       B               4                6
Area 2       D               6                6
Area 3       A               3                7
Area 3       C               4                7
Area 3       D               5                7

I'm unable to provide a reproducible example for this, as I haven't figured out how to provide the command the needed loop to iterate through the listing. As the calculation has to be area-based, I believe it should somehow be told to take into account the areas one by one (unique(DF$AREA)?). The quota is also a challenge for me because it is only needed 'by one value' as it is same for all parties in one particular area.

I also thought of 'splitting' the data for multiple new dataframes (area by area) by using

list2env(split(DF,DF$AREA),envir = .GlobalEnv)

which was successful but I don't consider this as a viable option as with multiple areas it makes the workspace very unorganized.

CodePudding user response:

disclaimer I have not worked with this package before, please take a careful look at the results.

  1. Preparing the data
df = structure(list(AREA = c("Area 1", "Area 1", "Area 1", "Area 2", 
"Area 2", "Area 3", "Area 3", "Area 3"), PARTYLABEL = c("A", 
"B", "C", "B", "D", "A", "C", "D"), PARTYSEATS = c(5, 2, 1, 4, 
6, 3, 4, 5), MAJORITY = c(5, 5, 5, 6, 6, 7, 7, 7)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -8L))
  1. Loading the packages and making the models for each area
library(tidyverse)
library(GameTheory)

out <- df %>%
  group_by(AREA) %>%
  nest() %>%
  mutate(models = map(data, ~ ShapleyShubik(head(.x[[3]], 1), .x[[2]], .x[[1]])))

based on the example ?ShapleyShubik I believe you are looking for something like the above.

Then summary can be called to extract some information.

lapply(out$models, summary)
  •  Tags:  
  • Related