2013-02-25 102 views
1

我正在通過單元格遍歷矩陣單元格,我想將所有小於1的值更改爲其負相反。這裏是循環我現在有在R中使用if語句的循環中出現錯誤

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

'Nmatrix [Nmatrix <1 < - -1/Nmatrix' – Andrie 2013-02-25 22:19:24

+4

今天第四次錯過了幾秒鐘的答案。就是這樣,我要去睡覺了。 – 2013-02-25 22:20:30

+1

好吧,@RomanLuštrik,我們早上會叫醒你 – 2013-02-26 01:03:36

回答

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 
+0

好。值得注意的是,OP得到原始錯誤的原因是矩陣中有一個「NA」。 – 2013-02-25 22:28:20