#create empty pelldata data frame
pelldata <- data.frame()

#create Additional data frame for approximate square root and square root difference columns
#add in 0 for the first values in each column
Additional <- data.frame(ApproxSqR=c(0),SqRtDiff=c(0))

#begin loop with a range of 1-200 to create 200 records
for(i in 1:200) {
  #add in if statement to create the first two values in pell and fibonacci sequence as these match the index of the loop
  if(i <= 2) {
    pelldata <- rbind(pelldata, data.frame(index=c(i),Pell=c(i-1),Fibonacci=c(i-1)))
  } else {
    #add to the data frame called pelldata using the rbind base function
    pelldata <- rbind(
                  pelldata,data.frame(
                    #creating the index column using the numerical value in the loop - 'i'
                    index=i, 
                    #calculating the Pell number for each row based on the index value
                    Pell=2*pelldata$Pell[i-1]+pelldata$Pell[i-2],
                    #calculating the Fibonacci number for each row based on the index value
                    Fibonacci=1*pelldata$Fibonacci[i-1]+pelldata$Fibonacci[i-2]
                  )
                )
  }
  #add to 'Additional' data frame with the approximate score route and square root difference columns 
  Additional <- rbind(Additional,
                      data.frame(
                        #calculate the approximate square root of each Pell number
                        ApproxSqR=(pelldata$Pell[i-1]+pelldata$Pell[i])/pelldata$Pell[i],
                        #calculate the difference of the square root number to the square root of 2
                        SqRtDiff=round(sqrt(2) - (pelldata$Pell[i-1]+pelldata$Pell[i])/pelldata$Pell[i], digits=5)
                      )
              )

}

#combine the the two data frames created in the loop using the cbind base function
pelldata <- cbind(pelldata,Additional)

#create a loop for the data frame to create and calculate how many decimal points the approximate square root is correct to
for(x in 1:length(pelldata$index)) {
  pelldata$SqRtDiffToDecimalPoint[x] <- nchar(sub(".*\\.(0*).*","\\1",pelldata$SqRtDiff[x]))
}

#clean up the data where the square root is correct to 5 decimal places as the regex above gives 0 reading
pelldata$SqRtDiffToDecimalPoint[which(pelldata$SqRtDiff == 0.00000)] <- 5

#change the options of the display to show whole numbers rather than scientific numbering
options(scipen=9999)

