-1

I am having some piece of R code where i need to multiply the elements that are not even in the matrix by two times

set.seed(75)
M <- matrix(sample(30, replace=T), nrow=5, ncol=5)

Fun4 <- function(M){
 for (i in 1:nrow(M)){
 for (j in 1:ncol(M)){
 if(M[i][j]%%2!=0){
  M[i][j] <- 2*M[i][j]
 }
 }
 }

Res <- Fun4(M)
print(Res)

In a matrix with random numbers, we want to multiply only the odd numbers by two, and then print our new matrix

when running the code i am hiving the error as :

Error in if(M[i][j]%%2!=0){:Missing value where True / False Needed

zx8754
  • 52,746
  • 12
  • 114
  • 209
  • 3
    Try `M[M%%2 == 1] <- M[M%%2 == 1]*2` – Sotos Jul 22 '19 at 09:56
  • Related possible duplicate https://stackoverflow.com/questions/9439619/replace-all-values-in-a-matrix-0-1-with-0 – zx8754 Jul 22 '19 at 10:01
  • Related: https://stackoverflow.com/questions/7355187/error-in-if-while-condition-missing-value-where-true-false-needed – zx8754 Jul 22 '19 at 10:03
  • 1
    Add, a closing `}` when defining the function, change `M[i][j]` to `M[i,j]` and change `<-` to `<<-` inside the function and your function should do what you want it to do on `M`. – GKi Jul 22 '19 at 10:15
  • @GKi doing global assignment with `<<-` is generally not a great practice / potentially dangerous – camille Jul 22 '19 at 17:49
  • @camille Yes. A better solution would be to write `M` before the missing closing bracket, because sital sharma is expecting that the function is returning `M`. – GKi Jul 23 '19 at 05:54

1 Answers1

0

To get the element in row i, column j of a matrix you need to use M[i,j]. You write M[i][j], and here M[i] gives the i-th element of the flattened matrix (a number), and when you try to take the j-th element of this number, for j>1 you get NA:

> M[1]
[1] 8
> M[1][1]
[1] 8
> M[1][2]
[1] NA
> M[1][2] %% 2 != 0
[1] NA
> if (M[1][2] %% 2 != 0) true
Error in if (M[1][2]%%2 != 0) true : 
  missing value where TRUE/FALSE needed

As others pointed out, you are also missing a closing bracket for your function definition.

jochen
  • 3,728
  • 2
  • 39
  • 49