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

时间秒杀一切 提交于 2019-12-02 01:42:51

问题


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.


回答1:


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

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