vendredi 8 juillet 2016

testing condition in matrix and vector

I would like to check this matrix m if it is <= 1 or >= 10. if so, I would like to change the value of another vector, val. if val is "A", then it should be changed to "B" and vice versa. If val is "C" it should be changed to "D" and vice versa. If no value is <= 1 or >= 10 in the matrix m then it should return val.

m
     x y
[1,] 2 11
[2,] 4 6
[3,] 5 6
[4,] 0 6
[5,] 2 6

val = "A"

the output should therefore be

out 
"B"

What I currently have is the following

x = m[, 1]
y = m[, 2]

x.test = any(x <= 1)
x.test = cbind(x.test, any(x >= 10) )

y.test = any(y <= 1) 
y.test = cbind(y.test, any(y >= 10) ) 

 if (any(x.test)==TRUE || any(y.test)==TRUE && val == 'A')
  { val2 = 'B'
} else if (any(x.test)==TRUE || any(y.test)==TRUE && val == 'B') 
  { val2 = 'A'
} else if (any(x.test)==TRUE || any(y.test)==TRUE && val == 'C') 
  {val2 = 'D'
} else if (any(x.test)==TRUE || any(y.test)==TRUE && val == 'D') 
  {val2 = 'C'
} else { val2 = val }

but it seems cumbersome and does not work well…

Aucun commentaire:

Enregistrer un commentaire