Module # 11 Debugging and defensive programming in R

 

Seek and Destroy: A Deliberate Bug in R

1) This week I tackle debugging a piece of code in R. Up until now I have only had to really deal with my own bugs, but now I tackle someone else's. This is meant to be like a puzzle which I usually enjoy so lets see how this one goes. 

2) The code I was given, and the error it is giving, is shown below:




3) Now as we can see, RStudio is not expecting "for (i in 1:nrow(x)) { outlier.vec[i] <- all(outliers[i,]) } return" to be where it is. To figure out what is causing this, we need to look at the code above this part. Reading through the whole thing we can see that on line seven, we are using two "&" symbols. Using "&&" instead of "&" causes only the first element of "outliers[, j]" to be compared with the result of "tukey.outlier(x[, j])", which does not correctly update outliers for the entire column. To fix this we can do the following:



4) As we can see above we have simply deleted one of the "&" symbols from line seven to  ensure that the logical comparison is applied to each element in the matrix. Leaving us with no more errors, that wasn't so bad. 

 

Comments

Popular posts from this blog

Module # 10 Building my own R package

Module # 13 Shiny Web App

Module # 4 Programming Structure