massivetotoro

Extracting 2CP from NSW local election (grouped) results files

May 29th, 2021
1,338
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. twocp_local<-function(x, grp1, grp2, grp3, percentage=FALSE){
  2.   x<-x[x$Type %in% c("RATL", "SATL"),]
  3.   output<-c(0,0,0,0)
  4.   firstprefs<-x[which(x$GroupCode==grp1 & x$PreferenceNumber==1),]
  5.   output[4]<-sum(firstprefs$Type=="SATL")
  6.   firstprefs<-x[which(x$GroupCode==grp1 & x$PreferenceNumber==1 & x$Type=="RATL"),]
  7.   all_ballots<-x[which((x$VCBallotPaperID %in% firstprefs$VCBallotPaperID) & x$Formality=="Formal" ),]
  8.   ballot_id<-unique(firstprefs$VCBallotPaperID)
  9.   for (i in 1:length(ballot_id)){
  10.     ballot<-all_ballots[all_ballots$VCBallotPaperID==ballot_id[i] & !is.na(all_ballots$PreferenceNumber),]
  11.     if (grp2 %in% ballot[,8] & grp3 %in% ballot[,8]){
  12.       result<-ifelse(ballot$PreferenceNumber[ballot$GroupCode==grp2]<ballot$PreferenceNumber[ballot$GroupCode==grp3], 1,2)
  13.       ifelse(!is.na(result), output[result]<-output[result]+1,output[3]<-output[3]+1)
  14.     }
  15.     else if (grp2 %in% ballot[,8] | grp3 %in% ballot[,8]){
  16.       result<-ifelse(grp2 %in% ballot$GroupCode,1,2 )
  17.       ifelse(!is.na(result), output[result]<-output[result]+1,output[3]<-output[3]+1 )
  18.     }
  19.     else{
  20.       output[3]<-output[3]+1
  21.     }
  22.   }
  23.   names(output)<-c(grp2, grp3, "Exhaust", "Single preference only")
  24.   print(paste("Preferences from", grp1))
  25.   if(percentage==TRUE){output<-prop.table(output)*100}
  26.   print(output)
  27. }
RAW Paste Data