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[p+1]>3+index[p])&(index[p+2]>3+index[p+1])){index[p+1]<-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?
Thanks in advance.
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)
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With