Unit Testing in R, A Silly Mistake

Unit testing. A powerful programming concept that is highly applicable to analytical work. Frameworks such as Excel do not offer quite the same ease of implementing unit tests, even within the scope of VBA.

Scripting languages such as R and MATLAB have strong unit testing libraries that are relatively easy to use and very powerful when appropriately applied. With that in mind, I started writing some unit tests in R for the first time today.

I figured this would be a breeze, so I threw together what I expected to be a really easy first test case only to encounter an oddly challenging problem.

test_that("Linear Weighted Mack Data Age 12-24", {
proper_result = round(8.206,3)
calculated_result = round(mLRs$linear$coefficients[1], 3)
expect_equal(proper_result, calculated_result)
})

I happened to know that this code worked, since I had just manually tested it, and so I expected a nice clean success.

Thanks R, for reminding me that no one is perfect. But, what drove me nuts, was the completely non-sensical error. 8.21 - 8.21 == 0 is a pretty clear logical success if I wanted the two figures to be equal. So I made adjustments .. I added a tolerance level to the expect equal of plus or minus 0.1. An extreme measure given that 8.21 == 8.21 rounded even to one decimal place, still to no avail.

So, I must be interpreting this wrong. Let's make a really terribly dumb failure case.

test_that("One equals to one, rounded.", {
proper_result = 1.000
calculated_result = round(2.0001,3)
expect_equal(proper_result, calculated_result)
})

Certainly, this would fail. Right?

Yes, as expected. The key confirmation I got is that the script is printing out the comparative values, showing me 1 - 2 == -1. Now, if you use R regularly, then you've probably already figured out what my problem is. I spend most of my time in MATLAB and so I forget to double up when pulling a value out of a list item. I guess MATLAB structs and matrices have spoiled me after all.

The long and short of this is ... the unit test results summary will not tell you that you have a type problem if you have a type problem. Instead, you'll get a silly A - A == 0 failure message. So, the proper code – for those not familiar with R:

test_that("Linear Weighted Mack Data Age 12-24", {
properresult = round(8.206,3)
calculatedresult = round(mLRs$linear$coefficients
[[1]], 3)
expectequal(properresult, calculatedresult)
})

And, voila, 8.206 now equals 8.206. When unit testing, remember to check your types very carefully when comparing – especially if you're teasing a number out of a list!

Photo Credits:

unsplash-logoIldefonso Polo