d'Hondt方法逆计算器

时间:2015-02-12 14:59:03

标签: r dirichlet

我从Carlos Gil Bellosta那里找到了代码,用d'Hondt方法分配选举系统中的座位。

# d'Hondt scores and counts
dHondt <- function(candidates, votes, seats){ 
  tmp <- data.frame( 
    candidates = rep( candidates, each = seats ), 
    scores     = as.vector(sapply( votes, function(x) x / 1:seats )) 
  ) 
  tmp <- tmp$candidates[order( - tmp$scores )] [1:seats]
  tmp <- as.data.frame(table(tmp)) [ ,2]
  return (tmp)
}

现在我想知道如何扭转这个功能,即从他们的座位开始估算n个党派的投票比例。

显然,这需要一个概率的方法。我试图模拟许多可能的结果并发现他们的座位等价,构建类似于概率表的东西。解?找到我所感兴趣的座位分布最近的n元组。看起来很老套,我知道。这是我的代码。

# sample results
generate <- function(distribution, threshold) {
  repeat {
    y <- rgamma(length(distribution), distribution, 1)
    if (all(y / sum(y) >= rep(threshold, length(distribution)))) {
      return (y/sum(y))
      break
    }
  }
}

# parameters
lookup <- c(7,6,3,2,2)
seats <- sum(lookup)
parties <- length(lookup)
names <- letters[1:parties]
threshold <- .05
sample <- 1E5 # there must be enough generated combinations for 6-7 parties gaining representation and parliaments up to 150 seats

# concentration parameters / priors for uniform dirichlet
priors <- rep(1, parties)
# priors <- c(7,6,3,2,2)   # change for a more concentrated random distribution near the relative values derived from these numbers

# percentages (base: votes for candidates over threshold)
p <- matrix(data=NA, nrow=sample, ncol=parties)
for(j in 1:sample){
  p[j, ] <- generate(priors, threshold)
  p[j, ] <- sort(p[j, ], decreasing = T)
}
p <- data.frame(p)
colnames(p) <- names

# seats
s <- matrix(data=NA, nrow=sample, ncol=parties)
for(j in 1:sample){
  s[j, ] <- dHondt(names, p[j, ], seats)
}
s <- data.frame(s)
colnames(s) <- names

# reverse lookup
i <- apply(s, 1, function(x) all(x == lookup))
s[i, ]
p[i, ]
summary(p[i, ])

如果有人建议可以以更优雅和直接的方式完成此事。

0 个答案:

没有答案