Skip to content

Instantly share code, notes, and snippets.

@smach
Last active March 1, 2016 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smach/09964691d70c4397fd78 to your computer and use it in GitHub Desktop.
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…
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