R/nominating.R

Defines functions nominating

Documented in nominating

#' Auxiliary Internal Functions
#'
#' @param parties See [simulate_election()].
#' @param lists_per_party See [simulate_election()].
#' @param rank_cand See [simulate_election()].
#' @param n_cand Numeric maximum number of candidates running in a party list; defaults to 0, which is internally interpreted as the district magnitude.
#' @param party_1 Boolean: Are we generating the last (only) party list? Defaults to `TRUE`.
#' @param party Optional numeric party ID. 
#' 
#'
#' @return data.frame with the following variable
#' \describe{
#' \item{rank}{List rank/position}
#' \item{candidate}{Candidate ID}
#' \item{pos}{Candidate's ideological position}
#' \item{list}{List ID}
#' \item{party}{Party ID}
#' }
#'
#' 
nominating <- function(parties, #vector of party positions
                       lists_per_party, #vector of nr. of lists fielded by each party
                       rank_cand, #true or false
                       n_cand, 
                       party_1 = TRUE,
                       party = NULL)
{
  tmp <- lapply(seq_along(parties), 
                function(x, lid = party_1, pid = party, party_pos = parties, n = n_cand, rank_c = rank_cand){
                  if(lists_per_party == 1){
                    res <- data.frame(rank = 1,
                                      candidate = NA,
                                      pos = rnorm(n, party_pos[x], 1),
                                      list = ifelse(lid, 1, x),
                                      party = ifelse(is.null(pid), x, pid))
                    if(rank_c){
                      res$rank <- order(abs(party_pos[x] - res$pos))
                    }
                    return(res)
                  } else {
                    list_seeds <- rnorm(lists_per_party, party_pos[x], 1)
                    nominating(list_seeds, 1, rank_cand, n_cand, FALSE, x)
                  }
                })
  nominated_party <- do.call(rbind, tmp)
  
  
  nominated_party <- nominated_party[order(nominated_party[,"party"],
                                           nominated_party[,"list"],
                                           nominated_party[,"rank"]),]
  nominated_party$candidate <- seq.int(nrow(nominated_party))
  return(nominated_party)
}

Try the i3pack package in your browser

Any scripts or data that you put into this service are public.

i3pack documentation built on June 8, 2025, 11:43 a.m.