有条件重新启动的行的增量计数 [英] Increment count over rows with conditional restarting
本文介绍了有条件重新启动的行的增量计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当要满足现有列中的条件时,我想增加一个从1开始的计数。
I would like to increment a count that restarts from 1 when a condition in an existing column is met.
例如,我有以下数据框:
For example I have the following data frame:
df <- data.frame(x1 = c(10, 100, 200, 300, 87, 90, 45, 80),
x2 = c("start", "a", "b", "c", "start", "k", "l", "o"))
我想创建 x3
,每次 x2 ==开始
。
结果数据框应如下所示:
The resulting data frame should look like this:
x1 x2 x3
1 10 start 1
2 100 a 2
3 200 b 3
4 300 c 4
5 87 start 1
6 90 k 2
7 45 l 3
8 80 o 4
我猜有R中提供了一般解决方案的现有功能。有人能指出我正确的方向吗?
I'm guessing there are existing functions in R that give a general solution. Can anyone point me in the right direction?
推荐答案
使用基数R:
df$x3 <- with(df, ave(x1, cumsum(x2 == 'start'), FUN = seq_along))
给予:
> df
x1 x2 x3
1 10 start 1
2 100 a 2
3 200 b 3
4 300 c 4
5 87 start 1
6 90 k 2
7 45 l 3
8 80 o 4
或使用 dplyr
或 data.table
软件包:
library(dplyr)
df %>%
group_by(grp = cumsum(x2 == 'start')) %>%
mutate(x3 = row_number())
library(data.table)
# option 1
setDT(df)[, x3 := rowid(cumsum(x2 == 'start'))][]
# option 2
setDT(df)[, x3 := 1:.N, by = cumsum(x2 == 'start')][]
这篇关于有条件重新启动的行的增量计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文