# 14-3 - Working With Lists

### 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

# getMinors  - 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.

getMinors<-function(x)
{
  # Check if the Size is Minor
  
  if (x[2]=="Minor")
  {
    # This returns a value only if the condition is TRUE
    return(x[1])
  }
  # If the condition is not TRUE then it will return a NULL
  
} # End of function getMinors

# getfast  - 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.


### Main Script ###

# Load data file

attendances<-read.csv("SP14/ThreeMonthsMin.csv", header=TRUE)

# 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)

# Get the names of all Minor units

minorUnits<-apply(attendances,1,getMinors)
typeof(minorUnits)

# minorUnits is now formatted as a list of lists
# We need to unlist it to get it back to a vector

minorUnits<-unlist(minorUnits)
typeof(minorUnits)

# minorUnits is now formatted as a character vector with a header
# We can convert it back to a pure vector of characters using as.vector

minorUnits<-as.vector(minorUnits)
typeof(minorUnits)

# minorUnits contains an element for every row in attendances
# Minor Units will have the hospital name
# Major units will contain NULL
# Select the unique elements using unique()

minorUnits<-unique(minorUnits)

minorUnits # Display the generated vector of characters