根据条件更改Matrix中的值

时间:2015-07-27 16:18:21

标签: r matrix apply

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

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不等于零,然后将xmat中的值替换为零,直到mat等于零,然后将值更改为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

1 个答案:

答案 0 :(得分:1)

你可以尝试

> 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