Recently I was working on my WIP package ‘verhoeff’, for calculating check digits based on the Verhoeff algorithim. I was at the stage where most of the basic code was written, so I was starting to test simple examples.

I was testing an early implementation which I thought would work. I used the code

calculate_digit(prepare_number(1), dat$d5, dat$d5_p, dat$inv_v)

In this code, prepare_number simply does some checks to see if the number is valid, and converts it to a numeric vector. The other arguments are the matrices needed for the Verhoeff math.

I got the error:

Error in d5_p[(i%%8) + 1, number + 1] + 1 : 
  non-numeric argument to binary operator

The traceback showed this came from the code

d5_p_calc <- function(d5_p, i, number) {
  d5_p[(i %% 8) + 1, number + 1] + 1
}

My first step in debugging this was to load the matrix I needed and write bits of the function by hand. I know that I use the %% operator, so I assumed one of its arguments was not numeric.

d5_matrix <- matrix(c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                        "1", "2", "3", "4", "0", "6", "7", "8", "9", "0",
                        "2", "3", "4", "0", "1", "7", "8", "9", "5", "6",
                        "3", "4", "0", "1", "2", "8", "9", "5", "6", "7",
                        "4", "0", "1", "2", "3", "9", "5", "6", "7", "8",
                        "5", "9", "8", "7", "6", "0", "4", "3", "2", "1",
                        "6", "5", "9", "8", "7", "1", "0", "4", "3", "2",
                        "7", "6", "5", "9", "8", "2", "1", "0", "4", "3",
                        "8", "7", "6", "5", "9", "3", "2", "1", "0", "4",
                        "9", "8", "7", "6", "5", "4", "3", "2", "1", "0"),
                      nrow = 10, ncol = 10)

# Here I'm breaking the problem down by dropping the final `+ 1`
d5_matrix[(1 %% 8) + 1, 3 + 1]
## [1] "4"

So that ran fine. Hmm, so the error cant be with %%. What happens if we add the final + 1 that is missing

d5_matrix[(1 %% 8) + 1, 3 + 1] + 1
## Error in d5_matrix[(1%%8) + 1, 3 + 1] + 1: non-numeric argument to binary operator

Ah ha! Now we’ve reproduced our error. So why does adding one to a matrix throw a non-numeric error?

Well if you look back at the matrix I created, you notice I did something veeeeery silly. All of the numbers that make up the matrix are quoted - so they make a character matrix not a numeric matrix. And you cant add the number 1 to a character.

Once I made the matrix integers instead of characters, it worked fine!