假设我们有以下矩阵:
M=structure(c(1, 2, 2, 2, 1, 3, 3, 4, 4, 6, 5, 5, 5, 6, 5, 5, 2,
2, 4, 1, 3, 1, 6, 4, 2, 5, 1, 3, 4, 6, 0.849542987113752, 0.849542987113752,
0.788371730579003, 0.788371730579003, 0.788371730579003, 0.788371730579003
), .Dim = c(6L, 6L), .Dimnames = list(NULL, c("", "", "", "",
"index", "cum_detection")))
根据其最后一行对矩阵M
进行排序:
index cum_detection
[1,] 1 3 5 4 2 0.8495430
[2,] 2 4 6 1 5 0.8495430
[3,] 2 4 5 3 1 0.7883717
[4,] 2 6 5 1 3 0.7883717
[5,] 1 5 2 6 4 0.7883717
[6,] 3 5 2 4 6 0.7883717
我正在搜索以获得以下输出:
index cum_detection
[1,] 1 3 5 4 2 0.8495430
[2,] 0 4 6 1 5 0.8495430
[3,] 0 4 0 3 1 0.7883717
[4,] 0 6 0 0 3 0.7883717
[5,] 0 0 0 6 4 0.7883717
[6,] 0 0 0 0 6 0.7883717
对于每一行,我们搜索从1到4的列.
如果我们发现一个值等于之前访问的行index
中的任何一个值,则将其替换为0
.
例如,考虑第三行M[3,1:4]
:
> M[3,1:4]
2 4 5 3
值2
和5
已经出现在先前的行index
列(M[1:2,"index"]
)中.
我相信解决方案是这样的:
t(apply(M,1,function(x) replace(x,M[1:current_row-1,"index"],0)))
其中current_row
是apply
循环的当前行.这里的问题是我不知道怎么弄到apply
current row index.