0

This is my code courtesy of How to get next number in sequence in R

seqNext <- function(x,n=1) {
  L <- length(x)
  dat <- data.frame(x=seq_along(x), y=x)
  seqGuess <- unname(
    predict(lm(y ~ poly(x, 2), data=dat), newdata=list(x=seq(L,L)))
  )
  seqAnswer <- tail(x, n=1)
  print(paste0("guess:",seqGuess," ","answer:",seqAnswer))
  if(seqGuess == seqAnswer){
    print("Correct")
  }
  else(
    print("Incorrect")
  )
}

readData <- function(){
  data <- read.csv("numberseries.csv", check.names = F)
  data
  apply(data,1,seqNext)
}

The data in question is a CSV file which looks like this:

174,232,290,348,406,464
180,210,240,270,300,330
1920,2016,2112,2208,2304,2400
3132,3190,3248,3306,3364,3422
510,540,570,600,630,660
638,696,754,812,870,928
2494,2552,2610,2668,2726,2784
1230,1260,1290,1320,1350,1380
3648,3744,3840,3936,4032,4128
2250,2280,2310,2340,2370,2400

Why is it that despite seqGuess == seqAnswer, I am receiving the printed value of "Incorrect" in some of these rows?

mryoloface
  • 11
  • 2
  • 3
    most likely a floating-point problem, https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal ; try `if (isTRUE(all.equal(seqGuess,seqAnswer)))` – Ben Bolker Aug 27 '19 at 13:55
  • closed as a duplicate, but didn't look in great detail. If someone explains that it's *not* a duplicate I will happily vote to reopen – Ben Bolker Aug 27 '19 at 14:01
  • @Ben Bolker Not sure if the question is a duplicate but I've tried the all.equal method and I receive an output of FALSE on all rows – mryoloface Aug 27 '19 at 14:16
  • Try using `if(all.equal(seqGuess, as.numeric(seqAnswer))==TRUE)`. The problem is one of your numbers is an integer and one is floating point. – MrFlick Aug 27 '19 at 14:22
  • @MrFlick thanks alot, kinda knew that was the problem but didn't know how to solve it. Cheers! Seems to work – mryoloface Aug 27 '19 at 14:29
  • @MrFlick worth reopening so you can answer? – Ben Bolker Aug 27 '19 at 14:46
  • @BenBolker. Nah. I would have closed with the same duplicate. I don't think this question well isolates the real problem to make it helpful to others in the future. – MrFlick Aug 27 '19 at 15:22

0 Answers0