Last active
March 1, 2016 01:31
-
-
Save smach/09964691d70c4397fd78 to your computer and use it in GitHub Desktop.
R function to find top vote-getter in a csv or Excel election results file. Requires rio package, and results file with candidate results in adjoining columns. findwinner function arguments: filename (string), datacolstart (number of data column where results data starts; 2 for column B in Excel, for example), datacolstop (number of the last dat…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function (filename, datacolstart, datacolstop, exportcsv = TRUE) | |
{ | |
if (!require("rio")) | |
install.packages("rio") | |
data <- rio::import(filename) | |
for(i in 1:nrow(data)){ | |
ranks <- rank(data[i,2:7]) | |
maxrank <- as.numeric(max(ranks)) | |
winners <- names(ranks[ranks==maxrank]) | |
data$Winners[i] <- paste(winners, collapse = ", ") | |
} | |
if (exportcsv) { | |
filename_root <- strsplit(filename, "\\.")[[1]][1] | |
filename_with_winner <- paste0(filename_root, "_winners.csv") | |
rio::export(data, filename_with_winner) | |
} | |
return(data) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment