简体   繁体   中英

cumsum is.na with rle ignoring consectives NA's

simple problem. Lets say I have the following data:

library(tidyverse)
df <- data.frame(group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2),
                     variable = c(NA, "a", NA, "b", "c", NA, NA, NA, NA, "a", NA, "c", NA, NA, "d", NA, NA, "a"))
df
   group variable
1      1     <NA>
2      1        a
3      1     <NA>
4      1        b
5      1        c
6      1     <NA>
7      1     <NA>
8      1     <NA>
9      1     <NA>
10     1        a
11     1     <NA>
12     1        c
13     1     <NA>
14     1     <NA>
15     1        d
16     2     <NA>
17     2     <NA>
18     2        a

I just want to count missing variables using cumsum(is.na(variable) but ignore consecutive missing ones so my desired output would look like:

   group variable newvariable
1      1     <NA>           1
2      1        a           1
3      1     <NA>           2
4      1        b           2
5      1        c           2
6      1     <NA>           3
7      1     <NA>           3
8      1     <NA>           3
9      1     <NA>           3
10     1        a           3
11     1     <NA>           4
12     1        c           4
13     1     <NA>           5
14     1     <NA>           5
15     1        d           5
16     2     <NA>           1
17     2     <NA>           1
18     2        a           1

I think I need to incorporate rle into my code:

df %>%
  group_by(group, na_group = {na_group = rle(variable); rep(seq_along(na_group$lengths), na_group$lengths)}) %>%
  mutate(newvariable = cumsum((is.na(variable)))) #?

Maybe map over groups could work. Any suggestions please?

Refs: Identify sets of NA in a vector Count consecutive values in groups with condition with dplyr and rle

df %>%
    group_by(group) %>%
    mutate(new = with(rle(is.na(variable)), rep(cumsum(values), lengths))) %>%
    ungroup()

Another option is to use diff with cumsum on the logical vector

library(data.table)
setDT(df)[, new := cumsum(c(TRUE, diff(is.na(variable)) > 0) ), group ]

Or with dplyr

library(dplyr)
df %>%
   group_by(group) %>%
   mutate(new = cumsum(c(TRUE, diff(is.na(variable)) > 0)))
# A tibble: 18 x 3
# Groups:   group [2]
#   group variable   new
#   <dbl> <fct>    <int>
# 1     1 <NA>         1
# 2     1 a            1
# 3     1 <NA>         2
# 4     1 b            2
# 5     1 c            2
# 6     1 <NA>         3
# 7     1 <NA>         3
# 8     1 <NA>         3
# 9     1 <NA>         3
#10     1 a            3
#11     1 <NA>         4
#12     1 c            4
#13     1 <NA>         5
#14     1 <NA>         5
#15     1 d            5
#16     2 <NA>         1
#17     2 <NA>         1
#18     2 a            1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM