用上面一行的相应元素替换等于矩阵零的每个元素 [英] Replace each element equal to zero of a matrix with the corresponding element of the row above

查看:120
本文介绍了用上面一行的相应元素替换等于矩阵零的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用R.我有一个矩阵,我想用上一行的相应元素替换等于0的每个元素.

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   

我想用元素AA [1,3]替换0. 我想要一个能够对矩阵的每个元素执行此操作的函数.

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.

推荐答案

我们可以找到矩阵('i1')中值为0的元素的行/列索引,然后通过以下方式提取对应于上面1行的元素:从'i1'中的row索引中减去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])]


或者将'0'更改为NA后,单线将使用library(zoo)中的na.locf


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)

这篇关于用上面一行的相应元素替换等于矩阵零的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆