Module 11 Debugging Assignment
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("logical", length = nrow(x))for (i in 1:nrow(x)) {outlier.vec[i] <- all(outliers[i, ])}return(outlier.vec)}set.seed(123)test_mat <- matrix(rnorm(50), nrow = 10)tukey_multiple(test_mat)corrected_tukey <- function(x) {outliers <- array(TRUE, dim = dim(x))for (j in seq_len(ncol(x))) {# FIX: use element-wise '&' instead of scalar '&&'outliers[, j] <- outliers[, j] & tukey.outlier(x[, j])}outlier.vec <- logical(nrow(x))for (i in seq_len(nrow(x))) {outlier.vec[i] <- all(outliers[i, ])}outlier.vec}corrected_tukey(test_mat)
Bug & Error (reproduced): Running the original tukey_multiple(test_mat) fails with
Error in outliers[, j] && tukey.outlier(x[, j]) : 'length = 10' in coercion to 'logical(1)'.
Diagnosis: The loop used &&, which is a scalar logical operator (evaluates only the first element). We need an element-wise operation across the whole column, so the correct operator is &.
Comments
Post a Comment