Remove isolated elements of a vector

We keep values where preceding or next difference is lower or equal to 4 :

v <- c(1,2,3,8,15,16,17)
v[c(FALSE, diff(v) <= 4) | c(diff(v) <= 4, FALSE)]

You can achieve it with a combination of outer and colSums, i.e.

x[colSums(abs(outer(x, x, `-`)) >= 4) == length(x)-1]
#[1] 8

To eliminate the values, we can do,

i1 <- colSums(outer(x, x, FUN = function(i, j) abs(i - j) >= 4)) == length(x) - 1
x[!i1]
#[1]  1  2  3 15 16 17

where,

x <- c(1,2,3,8,15,16,17)