gpt4 book ai didi

r - tidyverse : consecutive appearance of zeros

转载 作者:行者123 更新时间:2023-12-04 10:23:46 25 4
gpt4 key购买 nike

想生成一列b来自 a以至于

if a == 1 then b = 0 
else b = counting start from 1
then if a == 1 then b = 0
else b = counting start from 1

tb1 中所述以下。

我的工作示例如下:
library(tidyverse)
tb1 <-
tibble(
a = c(1, rep(0, 4), 1, rep(0, 5), 1, 1, rep(0, 4), 1, rep(0, 2))
, b = c(0, 1:4, 0, 1:5, 0, 0, 1:4, 0, 1:2)
)
tb1
#> # A tibble: 20 x 2
#> a b
#> <dbl> <dbl>
#> 1 1 0
#> 2 0 1
#> 3 0 2
#> 4 0 3
#> 5 0 4
#> 6 1 0
#> 7 0 1
#> 8 0 2
#> 9 0 3
#> 10 0 4
#> 11 0 5
#> 12 1 0
#> 13 1 0
#> 14 0 1
#> 15 0 2
#> 16 0 3
#> 17 0 4
#> 18 1 0
#> 19 0 1
#> 20 0 2

tb2 <-
tb1 %>%
mutate(b1 = if_else(condition = a == 1, true = 0, false = 1)) %>%
group_by(a) %>%
mutate(b2 = cumsum(b1))

tb2
#> # A tibble: 20 x 4
#> # Groups: a [2]
#> a b b1 b2
#> <dbl> <dbl> <dbl> <dbl>
#> 1 1 0 0 0
#> 2 0 1 1 1
#> 3 0 2 1 2
#> 4 0 3 1 3
#> 5 0 4 1 4
#> 6 1 0 0 0
#> 7 0 1 1 5
#> 8 0 2 1 6
#> 9 0 3 1 7
#> 10 0 4 1 8
#> 11 0 5 1 9
#> 12 1 0 0 0
#> 13 1 0 0 0
#> 14 0 1 1 10
#> 15 0 2 1 11
#> 16 0 3 1 12
#> 17 0 4 1 13
#> 18 1 0 0 0
#> 19 0 1 1 14
#> 20 0 2 1 15

最佳答案

一种选择可能是:

tb1 %>%
group_by(rleid = with(rle(a), rep(seq_along(lengths), lengths))) %>%
mutate(b = 1:n() * (a != 1))

a b rleid
<dbl> <int> <int>
1 1 0 1
2 0 1 2
3 0 2 2
4 0 3 2
5 0 4 2
6 1 0 3
7 0 1 4
8 0 2 4
9 0 3 4
10 0 4 4
11 0 5 4
12 1 0 5
13 1 0 5
14 0 1 6
15 0 2 6
16 0 3 6
17 0 4 6
18 1 0 7
19 0 1 8
20 0 2 8

关于r - tidyverse : consecutive appearance of zeros,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60720449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com