# 11-3 Variable Scope

# Simple scope demonstrator

testValues<-c(12,19,4,9,28,15) # Vector to loop through

maxValue<--999 # Vector defined outside loop

for (i in seq(testValues)) # loop counter
{
  currentValue<-testValues[i] # Vector defined inside loop
  
  print(paste("In loop: currentValue = ",currentValue))
  print(paste("In loop: maxValue = ",maxValue))
  print(paste("In loop: i = ",i))

  # Update maxValue if appropriate  
  if (currentValue>maxValue) maxValue<-currentValue 
}

print(paste("After loop: currentValue = ",currentValue))
print(paste("After loop: maxValue = ",maxValue))
print(paste("After loop: i = ",i))

# More complex example
# Calculate the total number of attendances at major and minor units

# Load data file

juneNumbers<-read.csv("SP10/JuneNumbers.csv", header=TRUE)

juneNumbers

# Initialise vectors for accessing data

minorTotal<-0 # Total for minor units (NOT loop counter)

majorTotal<-0 # Total for major units (NOT loop counter)

# Use a FOR loop to extract the data and manipulate it

for (i in 1:nrow(juneNumbers))
{
  
  # Save the attendance number into a local variable
  
  currentAttendance<-juneNumbers[i,"Attendances"]
  
  if (juneNumbers[i,"Size"]=="Major")
  {
    majorTotal<-majorTotal+currentAttendance # Update majorTotal
  }
  else 
  {
    minorTotal<-minorTotal+currentAttendance # Update minorTotal
  }
}

# Print out the results using paste() to concatenate strings

print(paste("Total attendance at Major units: ",majorTotal))
print(paste("Total attendance at Minor units: ",minorTotal))