# Remove isolated elements of a vector

• A+
Category：Languages

I have a vector of integers and I want to filter it by eliminating the components that are "isolated". What do I mean by "isolated"? those components that does not lie in an 4-neighbourhood of other component. The components in the vector are ordered increasingly, and there are no repetitions.

For example if I have `c(1,2,3,8,15,16,17)` then I need to eliminate `8` because is not in a 4-neighbourhood of other element.

I've tried applying

``   for (p in 1:(length(index)-2))       if((index>3+index)&(index>3+index)){index``<-0}       index<-index[index!=0] ``

where `index` is my vector of interest, but there's some problem with the logical condition. Could you please give me some hints?

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) ``