4

I want to recode the values in a matrix in such a way that all values <=.2 become 2, <=.4 become 3 etc. However, there are missings in my data, which I do not want to change (keep them NA). Here you find a simplified version of my code. Using na.omit works perfectly for the first changes

try <- matrix(c(0.78,0.62,0.29,0.47,0.30,0.63,0.30,0.20,0.15,0.58,0.52,0.64,
     0.76,0.32,0.64,0.50,0.67,0.27, NA), nrow = 19)
try[na.omit(try <= .2)] <- 2 #Indeed changes .20 and .15 to 2 and leaves the NA as NA

However, when I do the same for a higher category, the NA is also changed:

try[na.omit(try <= .8)] <- 5 #changes all other values including the NA to 5

Can someone explain to me what is the difference between the two and why the second one also changes the NA-value while the first one does not? Or am I doing something else wrong?

VandenEnden
  • 125
  • 1
  • 1
  • 5
  • 2
    You can just do `try[try <= .8] <- 5`. The NA will remain as such. or you can have a condition `try[try <=.8 & !is.na(try)] <- 5` – akrun Jan 29 '15 at 11:38
  • Thanks, I expected it too be pretty easy. I didn't try because `try[try <= .8]` did include the NA, but good to know that in changing the values this is not the case. – VandenEnden Jan 29 '15 at 11:44

1 Answers1

1

You can do

try[try <= .8] <- 5

The NA values will remain as NA

Or create a logical condition to exclude the NA values

try[try <=.8 & !is.na(try)] <- 5
akrun
  • 874,273
  • 37
  • 540
  • 662