# 13-1 UsingApply

### Function Definitions ###

# Calculateoverall - 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.

calculateoverall <- 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
  CW1<-as.numeric(x[3])
  CW2<-as.numeric(x[4])
  Exam<-as.numeric(x[5])

  # Calculate the mean, removing any NA values
  # Either of these two approaches will work
  
  #overall<-sum(CW1,CW2,Exam, na.rm=TRUE)/3
  overall<-mean(c(CW1,CW2,Exam), na.rm=TRUE)
  
  # Return the length-1 vector containing the sum
  return(overall)
  
} # End of function calculateoverall

# finalgrade - 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.

finalgrade <- function(x)
{
  # Extract values from the row as numbers
  # No conversion is needed. Although the first column of the data frame
  # is a vector of characters and R assumes that all columns are characters,
  # we only want to print them out, not calculate them, so we don't care
  surname<-x[2]
  overall<-x[6]
  
  # Create a length-1 character vector containing the pasted string
  result<-paste(surname,": ",overall)
  
  # Return the length-1 character vector
  return(result)
  
} # End of function finalgrade


### Main Script ###

# Load data file

examresults<-read.csv("SP13/Results.csv", header=TRUE)

# Calculate final mark
# apply(dataframe, 1=rows, function to be applied)

finalmark<-apply(examresults,1,calculateoverall)
finalmark # Display the generated vector

# Bind newly-created column finalmark onto the data frame with header 'final'
# It will have the right number of elements because one element was generated
# from each row of the original data frame

examresults<-cbind(examresults,Final=finalmark)

# Display module results
# apply(dataframe, 1=rows, function to be applied)

moduleresults<-apply(examresults,1,finalgrade)
moduleresults # Display the generated vector of characters