条件增量式 [英] Conditional increment tidyverse
问题描述
我一直在搜索如何在dydyverse中有条件地增加,但没有成功。我想做的是检查列中的值是否大于某些 x
,如果是,则将整数增加一。每个观察都从1开始。
I've been googling quite unsuccessfully how to increment conditionally in tidyverse. What I want to do is check if value in a column is greater than some x
, and if so increment an integer by one. Every observation starts with 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, ?, ?))
任何帮助将不胜感激。
推荐答案
这可以使用累积和来完成,累积和每次值大于100时都会增加,例如:
This can be done using a cumulative sum, which increments each time the value is greater than 100, for example:
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(...)
,以便从1 instad(从0开始)开始第一个组。并不是说,如果给定id组中的第一个值> 100,则该组可能从2开始。
I used 1 + cumsum(...)
in order to start the first group from 1 instad of 0. Not that a group might start with a 2 if the first value is >100 in a given id-group.
这篇关于条件增量式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!