#Author: ngoet
#First version: 7.8.2018
#This version: 10.8.2018

calcVoteLoyalty <- function(voteDat){

  Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
} 
  
  loyaltyDat <- data.frame(
    IdLegislativePeriod = numeric(),
    loyalty = numeric(),
    PersonNumber = numeric()
  )
  
  #split by legislative session
  voteDatPerLeg <- split(voteDat,voteDat$IdLegislativePeriod)
    
    #iterate through legislatures
    for(leg in 1:length(voteDatPerLeg)){
      
      thisLegDat <- voteDatPerLeg[[leg]]
      
      #now consider for each party how the majority voted for each issue
      majorityDecisionsPerPartyPerVote <- aggregate(Decision~ParlGroupCode + IdVote,data = thisLegDat,FUN=Mode)
      
      colnames(majorityDecisionsPerPartyPerVote) <- c("ParlGroupCode",
                                                      "IdVote",
                                                      "MajDecision")
      
      legDatPerMP <- split(thisLegDat,thisLegDat$PersonNumber)
      for(mp in 1:length(legDatPerMP)){
        thisLegDatPerMP <- legDatPerMP[[mp]]
        
        evaluationData <- merge(thisLegDatPerMP,majorityDecisionsPerPartyPerVote,by=c("IdVote","ParlGroupCode"))
        
        loyalty <- nrow(evaluationData[evaluationData$Decision ==evaluationData$MajDecision,])/nrow(evaluationData)
        
        loyaltyDat <- rbind(loyaltyDat,
                            data.frame(
                              IdLegislativePeriod = unique(evaluationData$IdLegislativePeriod),
                              loyalty = loyalty,
                              PersonNumber = unique(evaluationData$PersonNumber)
                            )
                            )
        
        message(paste("Calculated loyalty for MP ",
                    unique(evaluationData$PersonNumber)," (legislature = ",
                    unique(evaluationData$IdLegislativePeriod),  
                    "): ",loyalty,
                    sep = "")
        )
      } #end of MP loop
      
      
    } # end of legislature loop
    
    return(loyaltyDat) # return object
  } # end of function
  
  
  
