# 12-5 Exercise 3 - Restructuring of 11-4 Exercise 2 using functions

### Function Definitions ###

# Function locationsum(place, mydata)
# place=area name, mydata=data frame
# Returns a length-1 vector containing the sum of attendances for that area

areasum<-function(place,mydata)
{
  # Sum the number of patients treated across area 'place'
  
  # Set up counter for placeTotal (NOT a loop counter)
  
  placeTotal<-0
  print(place)
  
  for (i in 1:nrow(mydata)) 
  {
    currentArea<-mydata[i,"Area"]
    currentAttendances<-mydata[i,"Attendances"]
    if (currentArea==place)
    {
      placeTotal<-placeTotal+currentAttendances
    }
  }
  return(placeTotal)
  
} # End of areasum



# Function nthpatient(n,mydata)
# n=nth position, mydata=dataframe
# Returns nothing, but prints out string

nthpatient<-function(n, mydata)
{
  # Identify when the 85000th attendance occurred
  
  # The data is not ordered by month, so a simple way to approach this
  # is to sum the attendances for each month, then check each month
  # in turn to see if the cumulative total has reached 85000 yet
  
  # Set up a data frame to show the month and the total attendances
  # for the month (this could also be done with just the vectors)
  
  monthlyTotals<-c(0,0,0) # Attendances for June, July, August
  monthNames<-c("June","July","August")
  summary<-data.frame(month=monthNames,total=monthlyTotals) # Data frame
  
  # Go through each row of data and add the attendance to the monthly total
  # Use a FOR loop to handle every row of the data frame
  
  for (i in 1:nrow(mydata))
  {
    # Identify month and attendance for that month
    currentMonth<-mydata[i,"Month"]
    currentAttendance<-mydata[i,"Attendances"]
    
    # Increment the total for the correct month in the summary data frame
    # There are three possible conditions (June, July, August) so we must
    # use three seperate IF statements rather than an IFELSE
    # There is a SWITCH statement we will explore later in the module
    
    if (mydata[i,"Month"]=="Jun-19")# Update June Total
    {
      summary$total[1]<-summary$total[1]+currentAttendance 
    }
    if (mydata[i,"Month"]=="Jul-19") # Update July Total
    {
      summary$total[2]<-summary$total[2]+currentAttendance 
    }
    
    if (mydata[i,"Month"]=="Aug-19") # Update August Total
    {
      summary$total[3]<-summary$total[3]+currentAttendance 
    }
    
  } # End of FOR loop
  
  summary # Display the summary data frame (really useful for debugging)
  
  # Check to see if the total has passed 85000; if so, print the total
  
  currentMonth<-1 # Reassign currentMonth because it's a useful name
  runningTotal<-0 # Overall cumulative total
  i<-1 # loop variable
  
  # Keep incrementing until the running total reaches a certain value
  # This needs a WHILE loop as we don't know if it needs to process
  # every row in the summary data frame
  
  while(runningTotal<=n) # Only run until condition is met
  {
    runningTotal<-runningTotal+summary$total[i] # Update cumulative total
    i<-i+1 # increment the counter
  }
  
  # Output the month
  # Use i-1 to access the right row because we incremented i after
  # updating the running total in the WHILE loop
  
  print(paste("The",n,"th attendance occurred in ",summary$month[i-1]))
  
  
} # End of nthpatient



# Function generateframe(target, mydata)
# target=treatment target percentage, mydata=dataframe
# Returns the new data frame for display

# NB - This is a very simple restructuring. More sophisticated versions
# would use further functions to perform the repeated calculations

generateframe<-function(target, mydata)
{
  # Identify any hospitals that failed to treat target% of patients in 
  # under 12 hours in more than 1 month
  
  # It's easiest to do this by creating a data frame that records T/F
  # for each hospital for each month, then filtering it to identify
  # those hospitals which miss the target 2 or 3 times
  
  # Set up a data frame to show the hospital, the three months, and
  # the number of failing months
  
  hospitals<-unique(mydata$Hospital) # UNIQUE removes duplicates
  
  # The target columns will be calculated later, so use NA
  juneTarget<-NA # These will recycle to fill the full table
  julyTarget<-NA
  augustTarget<-NA
  
  # The number of failing months will be calculated later, so use NA
  failMonths<-NA
  
  # Build these columns into a data frame monthlyTargets
  
  monthlyTargets<-data.frame(hospital=hospitals,
                             june=juneTarget,
                             july=julyTarget,
                             august=augustTarget,
                             fails=failMonths) # Data frame
  
  # Display the data frame for debugging
  
  monthlyTargets
  
  # Go through each row of data and chack to see if 12 hour attendance
  # is less than target%. If it is, set the month target to FALSE, otherwise
  # set the month target to TRUE
  
  # Use a FOR loop to handle every row of the data frame
  
  for (i in 1:nrow(mydata))
  {
    # Identify month
    currentMonth<-mydata[i,"Month"]
    
    # Identify hospital
    currentHospital<-mydata[i,"Hospital"]
    
    # Identify rowID of currentHospital in monthlyTargets
    rowID<-0
    j<-1
    
    # Loop through monthlyTarget rows until monthlyTarget$hospital
    # is the same as current hospital
    while(rowID==0)
    {
      #print(monthlyTargets$hospital[j])
      if (monthlyTargets$hospital[j]==currentHospital) 
      {
        rowID<-j  # Set the value of rowID; this will exit the loop
      }
      j<-j+1 # Increment j to look at the next rown in monthlyTarget
    }
    
    # Check the target for the current row's month
    # There are three possible conditions (June, July, August) so we must
    # use three seperate IF statements rather than an IFELSE
    
    if (mydata[i,"Month"]=="Jun-19") # Set June flag
    {
      monthID<-2 # Column 2
      flag<-ifelse(mydata[i,"Under12Percentage"]<target,FALSE,TRUE)
    }
    
    if (mydata[i,"Month"]=="Jul-19") # Set July flag
    {
      monthID<-3 # Column 3
      flag<-ifelse(mydata[i,"Under12Percentage"]<target,FALSE,TRUE)
    }
    
    if (mydata[i,"Month"]=="Aug-19") # Set August flag
    {
      monthID<-4 # Column 4
      flag<-ifelse(mydata[i,"Under12Percentage"]<target,FALSE,TRUE)
    }
    
    # Fill in the appropriate month / hospital cell in monthlyTotals
    # with the current value of flag
    
    monthlyTargets[rowID,monthID]<-flag
    
  } # End of FOR loop
  
  monthlyTargets # Display the summary data frame (really useful for debugging)
  
  # Finally calculate the number of times the hospital missed the target
  
  for (i in 1:nrow(monthlyTargets)) # For each row in monthlyTargets
  {
    totalMissed<-0 # Counter for months missed
    
    # Loop through columns 2,3,4 - june, july, august
    for (j in 2:4)
    {
      # If the value is FALSE, increment the totalMissed counter
      if (monthlyTargets[i,j]==FALSE) totalMissed<-totalMissed+1
    }
    
    # Assign totalMissed to the fail column of the data frame
    monthlyTargets$fails[i]<-totalMissed
  }
  
  # Return the final data frame
  
  return(monthlyTargets)
  
}


### Main Script ###

# Load data file

patientdata<-read.csv("SP12/ThreeMonths.csv", header=TRUE)

# Sum data for Carmarthen

locationsum("Carmarthen", patientdata)

# Find the 120000th patient

nthpatient(120000, patientdata)

# Check targets for 92%

summarydata<-generateframe(92,patientdata)
summarydata
