Home > OS >  How to ignore NA when selecting values from a vector in R
How to ignore NA when selecting values from a vector in R

Time:01-12

Say I have

a <- c(0:3, NA)

and I wish to replace 0 with 1 and replace 1 with 0. Namely, I want a <- c(1, 0, 2, 3, NA). The following codes do not work because of NA

> a[a<2] <- 1- a[a<2]
Error in a[a < 2] <- 1 - a[a < 2] : 
  NAs are not allowed in subscripted assignments

I know we can use na.rm = T if we are using a function. How to add such argument in my case?

CodePudding user response:

Just subset the values 0 and 1 using %in% and subtract from 1 - %in% returns FALSE for NA values and only TRUE for the values that match the rhs, then we subtract 1 so that 1-1 = 0 and and 1-0 = 1

a[a %in% 0:1] <- 1 - a[a %in% 0:1]

-output

> a
[1]  1  0  2  3 NA

Or if we want to use the OP's code

a[a < 2 & !is.na(a)] <- 1 - a[a < 2 & !is.na(a)]
  •  Tags:  
  • r
  • Related