条件递增tidyverse

8

我一直在谷歌搜索如何在tidyverse中有条件地增量。我的目标是检查列中的值是否大于某个x,如果是,则将整数增加1。每个观察值都从1开始。

示例代码:

id = c(1, 1, 1, 2, 3, 3, 3, 3, 4)
time = c(20, 30, 101, 33, 50, 101, 30, 110, 30)

df_x = data.frame(id = id, time = time)

输出:

  id time
1  1   20
2  1   30
3  1  101
4  2   33
5  3   50
6  3  101
7  3   30
8  3  110
9  4   30

期望输出:

increment = c(1, 1, 2, 1, 1, 2, 2, 3, 1)

df_x$increment = increment

   id time increment
1  1   20         1
2  1   30         1
3  1  101         2
4  2   33         1
5  3   50         1
6  3  101         2 
7  3   30         2
8  3  110         3
9  4   30         1

该代码可能类似于:

df_x %>%
  group_by(id) %>%
  mutate(ifelse(time <= 100, ?, ?))

非常感谢您的帮助。

1个回答

13

可以使用累计求和来实现,每次值大于100时增加一次,例如:

df_x %>% 
  group_by(id) %>% 
  mutate(increment = 1 + cumsum(time > 100))

# A tibble: 9 x 3
# Groups:   id [4]
     id  time increment
  <dbl> <dbl>     <dbl>
1    1.   20.        1.
2    1.   30.        1.
3    1.  101.        2.
4    2.   33.        1.
5    3.   50.        1.
6    3.  101.        2.
7    3.   30.        2.
8    3.  110.        3.
9    4.   30.        1.

我使用了1 + cumsum(...),以便将第一组从0开始改为从1开始。请注意,在给定的id组中,如果第一个值> 100,则该组可能从2开始。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接