# Read in the csv file and make the strings column a factor

irisData<-read.csv("iris.csv", header=TRUE, stringsAsFactors = TRUE)
irisData
summary(irisData)


#Create function to loop through the data to get the counts

generateSummary<-function(x)
{

  # Create vector with the Species in
  species<-c("Iris-setosa","Iris-versicolor","Iris-virginica")
  species

  # Create vector for the count
  counts<-c(0,0,0)
  counts

  # Create the df frame the loop will add to
  irisSummary<-data.frame(Species=species,Num_Records = counts)
  irisSummary

  # Create the loop to get the counts

  #for each row of our data frame...

  for (i in seq(1:length(x$Species)))
  {
    # For each row of the summary table...
    for(j in 1:3)
    {
    
    # ... check to see which row of the summary table it refers to
      if (x[i,5]==irisSummary[j,1])
      {
      # If the names match, increment the relevant counter
        irisSummary[j,2]<-irisSummary[j,2]+1

      }

    }
  }

  # Return the completed summary data frame to the main script

  return(irisSummary)
}

# Run the function on IrisData to see the counts
generateSummary(irisData)


# Create table to calculate the Pearson Correlation between the petal length and the sepal length

lengthData<-data.frame(PetalLength = irisData$Petal.length, SepalLength =irisData$Sepal.length)
lengthData

cor(lengthData,method="pearson")

# Create a scatterplot of the petal length and sepal length

plot(x=lengthData$PetalLength, y=lengthData$SepalLength, xlab="Petal Length",ylab="Sepal Length",
     main="Petal Length vs. Sepal Length")


# Create a function to calculate the area of each record

calculateArea<-function(x)
{
  PetalArea<-NULL
  
  for (i in seq(1:length(x)))
  {
    if (x[i,5]=="Iris-setosa")
    {
      PetalArea[i] <- x[i,4] * x[i,3]*0.8
    }
    if (x[i,5]=="Iris-versicolor")
    {
      PetalArea[i] <- x[i,4] * x[i,3]*0.75
    }
    if (x[i,5]=="Iris-virginica")
    {
      PetalArea[i] <- x[i,4] * x[i,3]*0.65
    }
  }
x<- cbind(x,PetalArea)  
return(x)
}

# Run the function on IrisData to include the Petal Area as a field on the dataset

calculateArea(irisData)
