# Chocolate Data 2 - Convert to factors

### Function Definitions

# updateToFactor - Converts the numeric column to a factor
# Data frame column dfc and list of replacement values v passed to function
# Returns the factor form of the data column

updateToFactor<-function(dfc,v)
{
  # dfc is currently a numeric vector
  # We want to generate a character vector, so create a new NULL vector
  # that can have the appropriate elements added to it
  
  newValues<-NULL
  
  # Loop through each element of dfc and add the appropriate value
  # from v to the end of newValues to get a vector of characters that is
  # the same length as the original dfc column
  
  for(i in dfc)
  {
    newValues<-c(newValues,v[i])
  }

  # Convert newValues to a factor
  
  newValues<-factor(newValues)
  
  # Return newValues
  
  return(newValues)
}

### Main Script

# Load data file into data frame ChocolateData
# We want to work with categorical data, so use stringsAsFactors=TRUE

chocolateData<-read.csv("SP15/ChocolateDataCSV.csv", header=TRUE, stringsAsFactors = FALSE)

# display the data frame

chocolateData

# Convert WhoAte column to a factor

chocolateData$WhoAte<-factor(chocolateData$WhoAte)

# Update Location to become a factor

# Define the values to replace the numbers in the column to be factorised

newValues<-c("Bedford AAU","Bedford Pilgrim","Swindon Meldon","UHNS Haem")

# Call updateToFactor with Location and newValues

chocolateData$Location<-updateToFactor(chocolateData$Location,newValues)

# Define the values to replace the numbers in the column to be factorised

newValues<-c("Roses","Quality Street")

# The $Chocolate column starts at 0, not 1, so needs to be updated
# Add 1 to every element in chocolateData$Chocolate

chocolateData$Chocolate<-chocolateData$Chocolate+1

# Call updateToFactor with Location and newValues

chocolateData$Chocolate<-updateToFactor(chocolateData$Chocolate,newValues)

