1

我正在逐个单元格地循环遍历矩阵,并且我想将所有小于 1 的值更改为它们的负倒数。这是我目前拥有的循环

x <- 1:rowlength
y <- 1:colLength
for (i in x) {
    for (j in y) {
        Cell <- Nmatrix[i,j]
        if (Cell<=1) {Cell = -1/Cell}
    }
}

当我尝试运行代码时,我不断收到以下错误:

Error in if (Cell <= 1) { : missing value where TRUE/FALSE needed

我不确定我做错了什么。任何帮助深表感谢。

谢谢

4

1 回答 1

5

由于这是 R,因此您不需要循环:

set.seed(42)
Nmatrix <- matrix(runif(20, 0, 2), nrow=4)
Nmatrix
          [,1]      [,2]      [,3]      [,4]      [,5]
[1,] 1.8296121 1.2834910 1.3139846 1.8693445 1.9564529
[2,] 1.8741508 1.0381919 1.4101296 0.5108576 0.2349747
[3,] 0.5722791 1.4731766 0.9154836 0.9245856 0.9499942
[4,] 1.6608953 0.2693332 1.4382245 1.8800290 1.1206655

现在来点魔法:

Nmatrix[Nmatrix < 1] <- (-1/Nmatrix)[Nmatrix < 1]
Nmatrix
          [,1]      [,2]      [,3]      [,4]      [,5]
[1,]  1.829612  1.283491  1.313985  1.869344  1.956453
[2,]  1.874151  1.038192  1.410130 -1.957492 -4.255777
[3,] -1.747399  1.473177 -1.092319 -1.081566 -1.052638
[4,]  1.660895 -3.712873  1.438225  1.880029  1.120665
于 2013-02-25T22:25:52.297 回答