Chi square matrix residuals

Solution 1:

In your case, the returned residuals is a 4x4 matrix. Instead of using a matrix to take the results, the following solution uses a list instead. This way you can have matrices of different sizes.

With minimal changes from your original code:

chisqlist <- function(x) {
  names = colnames(x);  num = length(names)
  m = list()
  index = 1
  for (i in 1:(num-1)) {
    for (j in (i+1):num) {
      #browser()
      m[[index]] = chisq.test(x[, i, drop = TRUE],x[, j, drop = TRUE])$residuals
      index=index+1
    }
  }
  return (m)
}

Edit: I do prefer @ Onyambu's answer, which I didn't see. It would be faster than a nested for loop.