Module # 11 Debugging and defensive programming in R
The code below contains a 'deliberate' bug!
tukey_multiple <- function(x) {
outliers <- array(TRUE,dim=dim(x))
for (j in 1:ncol(x))
{
outliers[,j] <- outliers[,j] && tukey.outlier(x[,j])
}
outlier.vec <- vector(length=nrow(x))
for (i in 1:nrow(x))
{ outlier.vec[i] <- all(outliers[i,]) } return(outlier.vec) }
> Find the bug and fix it.
>>Report on your blog the success or failure in your debugging procedure.
After inputting the code into Rstudio, i get the result:
Error: unexpected symbol in:
" for (i in 1:nrow(x))
{ outlier.vec[i] <- all(outliers[i,]) } return"
After careful examination I noticed two issues. First, the structure of the function was not aligned properly. This had to be modified in order for Rstudio to recognize the function. Second, there appears to be &&. && only looks at the first value in each list and gives back a simple yes or no answer while ignoring all other values. If changed to &, each pair of values is compared.
I then created a dummy matrix of random numbers. > dummy_matrix <- matrix(c(48, 33, 37, 56, 12,
+ 94, 84, 55, 46, 46,
+ 19, 77, 15, 83, 62,
+ 16, 99, 11, 69, 87),
+ nrow = 5, ncol = 4, byrow = TRUE)
I performed tukey_multiple(dummy_matarix) and received this error below. This means tukey.outlier is not defined. This needs to be done.
> tukey_multiple(dummy_matrix)
Error in tukey.outlier(x[, j]) : could not find function "tukey.outlier"
The function below helps identified outliers and also defined tukey.outlier
> tukey.outlier <- function(x) {
+ Q1 <- quantile(x, 0.25)
+ Q3 <- quantile(x, 0.75)
+ IQR <- Q3 - Q1
+
+ lower_bound <- Q1 - 1.5 * IQR
+ upper_bound <- Q3 + 1.5 * IQR
+
+
+ return(x < lower_bound | x > upper_bound)
+ }
>
The code for tukey_multiple also had to be altered slightly. Below is what it looks like now.
> tukey_multiple <- function(x) {
+ outliers <- array(TRUE,dim=dim(x))
+ for (j in 1:ncol(x)){
+
+ outliers[,j] <- tukey.outlier(x[,j])
+ }
+ outlier.vec <- vector(length=nrow(x))
+ for (i in 1:nrow(x)) {
+ outlier.vec[i] <- all(outliers[i,])
+ }
+
+ return(outlier.vec)
+
+ }
>
Now after running the dummy matrix through tukey_multiple, the result is:
> tukey_multiple(dummy_matrix)
[1] FALSE FALSE FALSE FALSE FALSE
This assignment was a bit more challenging than I thought it would be. I really had to sit down and find what was wrong by carefully examining the code. Even after potentially finding what was wrong, I incorporated fake data to test the function. I was able to get a somewhat concrete answer. This assignment really helped me understand the process of debugging. I am sure I will be running into issues like this in the future whether it be my job or school. I will remember the steps I used on this assignment to tackle harder and trickier code.
Comments
Post a Comment