lundi 25 février 2019

Remove isolated elements of a vector

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.

Aucun commentaire:

Enregistrer un commentaire