Module 11: Debugging and Defensive Programming in R

 

For this assignment, I debugged a function that was supposed to identify rows in a numeric matrix that were outliers in every column using the Tukey rule. I first reproduced the bug by creating a test matrix with random values and running the original function.

When I ran the function, I got a warning showing that the logical expression was not being handled correctly. The issue was caused by using && inside the loop. In R, && only checks the first element of a logical vector, but this function needed an element-wise comparison across all rows. Because of that, the code was not correctly updating the outlier matrix.

To fix the problem, I replaced && with &. The & operator compares vectors element by element, which matches the purpose of the function. After making that change, the corrected version ran without warnings and returned a logical vector of length 10.

I also added defensive programming checks at the top of the function to make sure the input is a matrix and that it is numeric. If those conditions are not met, the function stops and gives a clear error message. This made the function safer and easier to debug.

This assignment helped me understand the difference between logical operators in R and why defensive checks are useful when writing functions.

 

 

 

Comments

Popular posts from this blog

Module 5: Determinant and Inverse of Matrices in R

Creating and Analyzing Data Frames in R

Module 10: Friedman R Package Proposal