我一直在谷歌上搜索如何在 tidyverse 中有条件地递增,但没有成功。我想要做的是检查列中的值是否大于某个 x
,如果是这样,则将整数加一。每个观察都从 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 时都会增加,例如:
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 of 0 开始第一组。如果给定 id-group 中的第一个值 >100,则该组可能以 2 开始。
关于r - 条件增量 tidyverse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51061268/