0

I am trying to add a scalar to a vector. However, when my scalar is NA, I want it to be ignored, similar to the na.rm = TRUE argument used in sum.

ie.

1:3 + x

returns NA NA NA if x is assigned NA. I would like it to return 1 2 3. I tried

sum(1:3, NA, na.rm = T)

but this does not vectorize the addition and just returns 1+2+3 = 6.

Is there a neat way to do this?

Thank you

Tim K
  • 61
  • 6

1 Answers1

1

You can use replace :

x <- NA
1:3 + replace(x, is.na(x), 0)
#[1] 1 2 3

x <- 2
1:3 + replace(x, is.na(x), 0)
#[1] 3 4 5
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178