Replace each element equal to zero of a matrix with the corresponding element of the row above
I'm using R. I have a matrix and I want to replace each element of it equal to zero with the corresponding element of the row above. For example, I created the following matrix: AA <- matrix(c(1,2,3,1,4,5,1,0,2), ncol=3, nrow=3) [,1] [,2] [,3] [1,] 1 1 1 [2,] 2 4 0 [3,] 3 5 2 I want to replace 0 with the element AA[1,3]. I would like a function able of doing this for each element of a matrix. We could find the row/column index of elements that are 0 in the matrix ('i1'), then extract the elements that correspond to 1 row above by subtracting one from the row index in 'i1' and replace the