2

我从 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, ])

想知道是否有人建议这可以以更优雅和直接的方式完成。

4

0 回答 0