3

I have a vector of numbers and want to check whether there is any zero that is surrounded by two identical numbers e.g.:

x <- c(3,0,3,4,5,2,0,1,3)

any(x == 0 & lag(x) == lead(x))
TRUE 

The problem is however that if the vector starts or ends with a 0, I will get a NA, because then either the lag or lead will be NA.

x <- c(0,3,4,5,2,0,1,3)

any(x == 0 & lag(x) == lead(x))
NA 

In this case I still want to return a FALSE. Does anyone know how to fix this perhaps with out using the lead- and lag-functions?

Thanks for your help!

1 Answers1

2

You need to check is.na and you can take advantage of the fact that NA & FALSE resolves to FALSE and TRUE | NA resolves to TRUE.

Try this:

any(!(is.na(lead(x)) | is.na(lag(x)) | lead(x) != lag(x) | x != 0))

This checks to see if all of your desired false cases are true, and then negates the overall expression.

x <- c(3,0,3,4,5,2,0,1,3)
any(!(is.na(lead(x)) | is.na(lag(x)) | lead(x) != lag(x) | x != 0))
[1] TRUE

x <- c(0,3,4,5,2,0,1,3)
any(!(is.na(lead(x)) | is.na(lag(x)) | lead(x) != lag(x) | x != 0))
[1] FALSE

Sometimes it is easier to check to see if the false case is true and negate.

Ben Norris
  • 4,733
  • 2
  • 5
  • 14