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 original value.
i1 <- which(!AA, arr.ind=TRUE)
AA[i1] <- AA[cbind(i1[,1]-1,i1[,2])]
Or a one-liner would be using na.locf
from library(zoo)
after changing the '0' to NA
library(zoo)
na.locf(replace(AA, !AA, NA))
If we code-golf, a more compact option would be
na.locf(AA*NA^!AA)
来源:https://stackoverflow.com/questions/35384492/replace-each-element-equal-to-zero-of-a-matrix-with-the-corresponding-element-of