Finding groups of nonzero elements using R

I have the following problem and I cannot find a simple solution.

I would like to find groups of non-zero elements in a vector (separated by at least one zero) and assign an id to each group (subsequent integer). For example, in a vector there value <- c(1,1,2,3,4,3,0,0,0,1,2,3,9,8,0,0,3,2)should be three groups: [1,1,2,3,4,3], [1,2,3,9,8], [3,2], so I would like to get such a data frame :

   value id
1      1  1
2      1  1
3      2  1
4      3  1
5      4  1
6      3  1
7      0 NA
8      0 NA
9      0 NA
10     1  2
11     2  2
12     3  2
13     9  2
14     8  2
15     0 NA
16     0 NA
17     3  3
18     2  3
+6
source share
5 answers

Use rle(). First create a new vector replacing the zeros of NA.

x <- match(value != 0, TRUE)
with(rle(!is.na(x)), {
    lv <- lengths[values]
    replace(x, !is.na(x), rep(seq_along(lv), lv))
})
# [1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3
+6
source

You may try:

as.integer(factor(cumsum(value==0)*NA^(value==0)))
#[1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3
+11
source

:

id <- (value>0)^NA
x <- rle(value>0)$lengths[c(TRUE, FALSE)]
id[!is.na(id)] <- rep(seq_along(x), times=x)

#[1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3
+1

:

ifelse(value != 0, 
       cumsum(value != 0 & dplyr::lag(value) %in% c(0, NA)), 
       NA)

# [1]  1  1  1  1  1  1 NA NA NA  2  2  2  2  2 NA NA  3  3
+1
  • You need to define a vector of vectors, so in v [0] you will find all the values ​​of the first group, and in v [1] you will find all the values ​​of the second group, etc.,
  • You need to loop all the values ​​when you find the null value. Continue until you find zero. Increase the vector by one and add a value, etc.,

I want this answer to be helpful.

-2
source

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


All Articles