我一直在谷歌搜索如何在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, ?, ?))
非常感谢您的帮助。