根据条件更改矩阵中的值

Changing Values in a Matrix based on a condition

所以我看过很多关于通过矩阵的一些简单索引将矩阵中小于等于零的特定数字的所有值更改为零的帖子。但我认为我拥有的东西更先进一些,我遇到了一些麻烦所以希望你们能帮忙。这是我正在使用的代码:

x <- (1:5)
y <- c(0,10,0,0,8)
n <- 12 

mat <- t(sapply(y, function(test) pmax(seq(test, (test-n+1), -1), 0) ))
mat

这会产生:

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]    0    0    0    0    0    0    0    0    0     0     0     0
[2,]   10    9    8    7    6    5    4    3    2     1     0     0
[3,]    0    0    0    0    0    0    0    0    0     0     0     0
[4,]    0    0    0    0    0    0    0    0    0     0     0     0
[5,]    8    7    6    5    4    3    2    1    0     0     0     0

xmat <- replicate(ncol(mat),x)

然后我想找出哪个y不等于0,然后将xmat中的值替换为零,直到mat等于0,然后将值更改为x值。所以下面是我目前拥有的。

CountTest <- which(y != 0)

xmat[CountTest,] <- apply(xmat[CountTest,], 1, function(xu) ifelse(xu > 0, 0, xu))
xmat

这会产生:

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]    1    1    1    1    1    1    1    1    1     1     1     1
[2,]    0    0    0    0    0    0    0    0    0     0     0     0
[3,]    3    3    3    3    3    3    3    3    3     3     3     3
[4,]    4    4    4    4    4    4    4    4    4     4     4     4
[5,]    0    0    0    0    0    0    0    0    0     0     0     0

期望的输出是:

       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]    1    1    1    1    1    1    1    1    1     1     1     1
[2,]    0    0    0    0    0    0    0    0    0     0     2     2
[3,]    3    3    3    3    3    3    3    3    3     3     3     3
[4,]    4    4    4    4    4    4    4    4    4     4     4     4
[5,]    0    0    0    0    0    0    0    0    5     5     5     5

你可以试试

> xmat*(mat==0)
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
#[1,]    1    1    1    1    1    1    1    1    1     1     1     1
#[2,]    0    0    0    0    0    0    0    0    0     0     2     2
#[3,]    3    3    3    3    3    3    3    3    3     3     3     3
#[4,]    4    4    4    4    4    4    4    4    4     4     4     4
#[5,]    0    0    0    0    0    0    0    0    5     5     5     5