1

I am looping through a matrix cell by cell and I want to change all of the values less than 1 to their negative reciprocal. Here is the loop I currently have

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

I keep getting the following error when i try to run the code:

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

I am not sure what I am doing wrong. Any help is much appreciated.

Thanks

3
  • 4
    Nmatrix[Nmatrix < 1] <- -1/Nmatrix Commented Feb 25, 2013 at 22:19
  • 4
    Missed an answer by a few seconds for the fourth time today. That's it, I'm going to bed. Commented Feb 25, 2013 at 22:20
  • 1
    OK, @RomanLuštrik, we'll wake you in the morning Commented Feb 26, 2013 at 1:03

1 Answer 1

5

Since this is R, you don't need a loop for this:

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

Now for some magic:

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
Sign up to request clarification or add additional context in comments.

1 Comment

Good. It's worth noting that the reason the OP got the original error is that there is an NA somewhere in the matrix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.