'Error of 'argument is of length zero' in R

I have a 18x18 matrice of 1s and 0s. However I have this below code that adds padding to the matrix to make it 20x20 and then check the neighbours of each element of a matrice if any matrice has all of its neighbours combined just as 1.

counter = 0
  
  imageNewMatrix <- imageMatrix
  
  nrow(imageMatrix)
  ncol(imageMatrix)
  
  imageNewMatrixa <- cbind(imageNewMatrix, 0)
  imageNewMatrixB <- rbind(imageNewMatrixa, 0)
  imageNewMatrixC <- cbind(imageNewMatrixB, 0)
  imageNewMatrixD <- rbind(imageNewMatrixC, 0)
  nrow(imageNewMatrixD)
  ncol(imageNewMatrixD)
 
  for (row in 1:nrow(imageNewMatrixD)) {
    for (col in 1:ncol(imageNewMatrixD)) {
      if (imageNewMatrixD[row,col] == 1) {
        
        # Get entry of the left pixel
        
        pixel_to_left = as.numeric(imageNewMatrixD[row, col-1])
        
        # Get entry of the right pixel
        
        pixel_to_right = as.numeric(imageNewMatrixD[row, col+1])
        
        # Get entry of the pixel at top
        
        pixel_at_top = as.numeric(imageNewMatrixD[row-1, col])
        
        # Get entry of the pixel at top-left
        
        pixel_at_top_left = as.numeric(imageNewMatrixD[row-1, col-1])
        
        # Get entry of the pixel at top right
        
        pixel_at_top_right = as.numeric(imageNewMatrixD[row-1, col+1])
        
        # Get entry of the pixel at bottom
        
        pixel_at_bottom = as.numeric(imageNewMatrixD[row+1, col])
        
        # Get entry of the pixel at bottom left
        
        pixel_at_bottom_left = as.numeric(imageNewMatrixD[row+1, col-1])
        
        # Get entry of the pixel at bottom right
        
        pixel_at_bottom_right = as.numeric(imageNewMatrixD[row+1, col+1])
        
        
        pixel_sum = pixel_to_left + pixel_to_right + pixel_at_top +
          pixel_at_top_left + pixel_at_top_right + pixel_at_bottom +
          pixel_at_bottom_left + pixel_at_bottom_right
        
        
        if (as.numeric(pixel_sum == 0)) {
          counter = counter + 1
        } else {
          counter = 0
        }
      
        
        
      }
    }
    
  }
  
  neigh_1 = counter

Whenever I try to run this code, the error Error in if (as.numeric(pixel_sum == 0)) { : argument is of length zero shows up. Can someone help me with this error?

r


Solution 1:[1]

I made a mistake of seeking for columns from n to nrow. Instead I used 2:19 cols and 2:19 rows.

I also used isTRUE when checking if pixel sum is equal to 0 or not.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dennis Main