flying sheep
flying sheep

Reputation: 8942

subscripted assignment ignoring NAs

I have a scoring matrix which I want to normalize. In order to do that, I simply want to divide all negative values by the minimum value and all positive ones by the maximum one (which conveniently makes every value positive and between 0 and 1, with two ones in the matrix).

This would nicely do, if there weren’t NAs.

scores[scores < 0] <- scores[scores < 0] / min(scores, rm.na=T)
scores[scores > 0] <- scores[scores > 0] / max(scores, rm.na=T)
scores

I just want to ignore the NAs and treat them as FALSE. min and max already nicely deal with NAs when specified, but is there a way to make </> behave like that, too?

e.g. the following applies:

 1 NA             T T
NA  2   >  0  ==  T T
-1 -2             F F

How to do

 1 NA             T F
NA  2   ?  0  ==  F T
-1 -2             F F

Upvotes: 1

Views: 511

Answers (1)

Justin
Justin

Reputation: 43255

Use a more complex boolean condition:

x <- scores < 0 & !is.na(scores)

scores[x] <- scores[x] / min(scores[x])

Upvotes: 2

Related Questions