Extract alternating sequence from vector to R

I have data similar to the following:

A= c(0,0,0,-1,0,0,0,1,1,1,0,0,-1,0,0,-1,-1,1,1,1,-1,0,0,0,-1,0,0,-1,-1,1,1,0,0,0,0,1,-1)

The goal is to extract alternating -1s and 1s. I want to create a function in which the input vector contains 0.1 and -1. The output ideally selects all 0s and alternates -1s and 1s.

For example, the desired result for the above example:

 B= c(0,0,0,-1,0,0,0,1,0,0,0,0,-1,0,0,0,0,1,0,0,-1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,-1)

Two 1s in 9th and 10th places are rotated by 0, because we only save the first 1 or -1. For this reason, -1s in the 16th and 17th positions of A for this reason also rotate to 0.

Does anyone have a good idea to create such a function?

+4
source share
3 answers

Determine the positions of non-zero values:

w = which(A != 0)

, A[w], :

library(data.table)
wkeep = tapply(w, rleid(A[w]), FUN = function(x) x[1])

:

# following @alexis_laz approach
B = numeric(length(A)) 
B[ wkeep ] = A[ wkeep ]

, , R , .


rleid data.table. R wkeep @alexis_laz:

wkeep = w[c(TRUE, A[w][-1L] != A[w][-length(w)])]

rleid, Josh answer.

+5

GWarius. ( , , .)

last1 <- -A[which(A != 0)[1] ] # The opposite of the first non-zero item
for (i in seq_along(A) ){ 
          if( last1==1 &&  A[i]==-1  ){ last1 <- -1
          } else {if (last1 == -1 && A[i] == 1) { last1 <- 1
                 } else {A[i] <- 0}} }
 A
 [1]  0  0  0 -1  0  0  0  1  0  0  0  0 -1  0  0  0  0  1  0  0 -1  0  0
[24]  0  0  0  0  0  0  1  0  0  0  0  0  0 -1

> identical(A, B)
[1] TRUE
+3

, , 1 -1. :

while i < length(a):

   if flag == 1 && a[i]=-1:
      b[i]=a[i];
      flag = -1;
   else if flag == -1 && a[i] = 1:
      b[i]=a[i];
      flag = 1;
   else:
      b[i]=0;
   i++;
}//end of while
+2

Source: https://habr.com/ru/post/1628388/


All Articles