Detect single values surrounded by NaN/NA pattern

Viewed 51

I am looking for a pattern to detect values that are surrounded by NAs or NaNs.

My data looks like this:

c(1,2,3,NA,NaN,NA,6,9,10,NaN,NA,12,20,NA,NaN,12,NA,45,100,NA,200,NA,NaN,300)

I need to know all single trapped values that are either between NA or NaN.

The result from the above example would be: c(12, 200)

Any elegant ideas?

3 Answers

Using lag and lead function from dplyr you can do -

library(dplyr)

x[!is.na(x) & is.na(lag(x, default = 1)) & is.na(lead(x, default = 1))]
#[1]  12 200

This basically returns a non-NA value trapped between NA values.

  1. Replace all NA with X
  2. collapse to vector with one string element
  3. use str_extract with regex:
library(stringr)

#data
vector <- c(1,2,3,NA,NaN,NA,6,9,10,NaN,NA,12,20,NA,NaN,12,NA,45,100,NA,200,NA,NaN,300)

vector[is.na(vector)] <- "X"
vector1 <- paste(vector,collapse=" ")
unlist(str_extract_all(vector1, "(?<=X )\\d+(?= X)"))

Output:

[1] "12"  "200"

We can use shift from data.table

library(data.table)
x[!is.na(x) & is.na(shift(x, fill = 1)) & is.na(shift(x, type = 'lead', fill = 1))]

-ouptut

[1]  12 200
Related