-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInference_Imputation.R
More file actions
executable file
·71 lines (66 loc) · 2.29 KB
/
Inference_Imputation.R
File metadata and controls
executable file
·71 lines (66 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env Rscript
#
#
library(boot)
library(dplyr)
library(tidyr)
library(vote)
########################################################################
load("resWI.RData") # consists of res.party
bootstrap_res_party <- function(condorcet_obj, R = 10000, ncpus = 38) {
profil <- condorcet_obj[['data']]
boot.fun <- function(data, indices) {
boot_sample <- data[indices, ]
result <- tryCatch(
condorcet(boot_sample, quiet = TRUE),
error = function(e) return(NULL) # Return NULL if no Condorcet winner exists
)
# if $elected is NULL, then this loop:
if (is.null(result) || is.null(result$elected)) {
if (!is.null(condorcet_obj[["totals"]])) {
totals_df <- condorcet_obj[["totals"]] %>%
as.data.frame() %>%
mutate(wins = rowSums(.))
win_counts <- table(totals_df$wins)
# depending on the loop, the following will be returned:
if (any(win_counts == 2)) {
return("Tie") # There is a win-value twice
} else if (any(win_counts == 3)) {
return("Cycle") # There is a win-value in a triple of times
} else {
return("Tie") # Else: Tie (like two ties)
}
} else {
return("nototals") # this case considers is.null(totals) == TRUE
}
} else { ## end of loop
return(result$elected[1]) # Return the first elected candidate
}
}
# run bootstrap
boot(data = profil,
statistic = boot.fun,
R = R,
parallel = "multicore", # For Linux/Unix
ncpus = ncpus)
}
set.seed(55234)
boot_results <- lapply(res.partyWI,
function(obj) bootstrap_res_party(obj,
R = 10000,
ncpus = 38))
# summarise results
elected_list <- boot_results %>%
purrr::map(~ as.data.frame(.x$t)) %>%
bind_cols() %>%
setNames(names(res.partyWI))
cwinner_party.df <- elected_list
rm(elected_list)
summary.df <- cwinner_party.df %>%
pivot_longer(cols = everything(), names_to = "case", values_to = "result") %>%
# gather(key = "case", value = "result") %>%
group_by(result) %>%
summarise(count = n())
print(summary.df)
write.csv(cwinner_party.df, "bootstrapWI.csv",
row.names = F)