Module 11 Debugging and Defensive Programming

 The code we have been given:

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) }

Running this in R Studio produces the error:

Error: unexpected symbol in:
"  for (i in 1:nrow(x))
  { outlier.vec[i] <- all(outliers[i,]) } return"

Looking at the code we can see that the bug is that we’re using the && operator inside the loop where we should be using the & operator. The && operator is not vectorized and only looks at the first element of the vector, whereas the & operator performs element-wise logical operations. Along with this, the return statement is causing an error as it is inside the second for loop, when it should be outside of it. Implementing these two fixes gives us this new code:

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) }

Which successfully runs the code and creates the function "tukey_multiple".






Comments