Replace each element equal to zero of a matrix with the corresponding element of the row above

拥有回忆 提交于 2019-12-02 00:18:53

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!