r - Replacing consecutive zeros with a desired value -


let's have matrix (or vector) of form

>set.seed(1) >x=ifelse(matrix((runif(30)),ncol = 2)>0.4,0,1)        [,1] [,2]  [1,]    1    1  [2,]    1    1  [3,]    0    1  [4,]    0    0  [5,]    1    1  [6,]    0    0  [7,]    0    0  [8,]    0    0  [9,]    0    1 [10,]    1    0 [11,]    1    0 [12,]    1    0 [13,]    0    1 [14,]    1    0 [15,]    0    0     ...     etc 

how can count number of consecutive zeros between ones in each column , replace zeros 1 these have count less predefined constant k. or @ least start index , number of elements in each sequence of zeros. there more zeros ones in data set, , of time length of sequence greater k

so, example, if k=1, [4,2];[13,1] , [15,1] going replaced 1. if k=2 in addition [4,1];[13,1] , [15,1], zeros in [3,1],[4,1], [14,2], , [15,2] going replaced 1 in example.

of course, can run loop , go through rows. wonder if there package, or neat vectorization trick can it.

update:

desired output example k=1

      [,1] [,2]  [1,]    1    1  [2,]    1    1  [3,]    0    1  [4,]    0    1  [5,]    1    1  [6,]    0    0  [7,]    0    0  [8,]    0    0  [9,]    0    1 [10,]    1    0 [11,]    1    0 [12,]    1    0 [13,]    1    1 [14,]    1    0 [15,]    1    0 

desired output k=2

      [,1] [,2]  [1,]    1    1  [2,]    1    1  [3,]    1    1  [4,]    1    1  [5,]    1    1  [6,]    0    0  [7,]    0    0  [8,]    0    0  [9,]    0    1 [10,]    1    0 [11,]    1    0 [12,]    1    0 [13,]    1    1 [14,]    1    1 [15,]    1    1 

the run-length tool rle works here:

fill_shortruns <- function(x,k=1,badval=0,newval=1){     apply(x,2,function(x){         r <- rle(x)         r$values[ r$lengths <= k & r$values == badval ] <- newval         inverse.rle(r)     }) }  # smaller example  set.seed(1) x0=ifelse(matrix((runif(10)),ncol = 2)>0.4,0,1) #      [,1] [,2] [,3] [,4] # [1,]    1    0    1    0 # [2,]    1    0    1    0 # [3,]    0    0    0    0 # [4,]    0    0    1    1 # [5,]    1    1    0    0  fill_shortruns(x0,2) #      [,1] [,2] [,3] [,4] # [1,]    1    0    1    0 # [2,]    1    0    1    0 # [3,]    1    0    1    0 # [4,]    1    0    1    1 # [5,]    1    1    1    1 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -