【问题标题】:Error in double for loop with if statement in R使用 R 中的 if 语句在双 for 循环中出错
【发布时间】:2013-02-25 22:16:40
【问题描述】:

我正在逐个单元格地循环遍历矩阵,我想将所有小于 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

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

谢谢

【问题讨论】:

  • Nmatrix[Nmatrix &lt; 1] &lt;- -1/Nmatrix
  • 今天第四次错过了几秒钟的答案。就这样,我要睡觉了。
  • 好的,@RomanLuštrik,我们早上会叫醒你

标签: r if-statement for-loop


【解决方案1】:

因为这是 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

【讨论】:

  • 好。值得注意的是,OP得到原始错误的原因是矩阵中的某处有一个NA。
猜你喜欢
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 2020-05-25
  • 2021-01-10
相关资源
最近更新 更多