# 14-2-Exercise 1

### Function Definitions ###

# calculateOver12 - this will be applied to each row of the data frame
# The data frame row is referenced as 'x'
# Each element of the row is referenced as x[1], x[2], x[3] etc.

calculateOver12<-function(x)
{
  
  # Extract values from the row as numbers
  # The conversion is needed because the first column of the data frame
  # is vector of characters, so R assumes that all columns are characters
  totalAttendances<-as.numeric(x[3])
  under12Attendances<-as.numeric(x[6])
  
  # Calculate the number over 12 hours

  over12value<-totalAttendances-under12Attendances
  
  # Return the length-1 vector containing the difference
  return(over12value)
} # End of function calculateOver12



### Main Script ###

# Load data file

attendances<-read.csv("SP14/ThreeMonthsMin.csv", header=TRUE, stringsAsFactors = FALSE)

# Calculate numbers waiting more than 12 hours
# apply(dataframe, 1=rows, function to be applied)

over12<-apply(attendances,1,calculateOver12)
over12 # Display the generated vector

# Bind newly-created column over12 onto the data frame with header 'Over12'
# It will have the right number of elements because one element was generated
# from each row of the original data frame

attendances<-cbind(attendances,Over12=over12)
