r - cumsum is.na rle 忽略 conectives NA

标签 r dplyr sequence seq run-length-encoding

简单的问题。假设我有以下数据:

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

我只想使用 cumsum(is.na(variable) 计算丢失的变量但忽略连续丢失的变量所以我想要的输出看起来像:

   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

我想我需要将 rle 合并到我的代码中:

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)))) #?

也许 map over groups 可以工作。有什么建议吗?

引用资料: 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()

关于r - cumsum is.na rle 忽略 conectives NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58397806/

相关文章:

R 通过对前 n 个最近日期进行子集化来转换日期表

r - Shiny 模块中 updateNavbarPage() 函数的范围问题

r - 如何在 R 中将 mutate_at() 与两组变量一起使用

r - 如何将当前行的负值传输到数据帧中的前一行?

r - 使用 dplyr 添加另一个分组

matlab - 删除重复项 - ** 仅当重复项按顺序出现时

generics - 通用序列

r - 无法复制此 ggplot2 图

python - 在 Python 中生成一个数字序列

r - ggplot 和 plot 如何以不同方式处理 inf 值?