【发布时间】:2021-04-02 22:01:18
【问题描述】:
我有一个如下所示的数据框:
d b c a
1 3400 100 3 -1
2 3400 50 3 1
3 3400 100 1 -1
4 3408 50 1 1
5 3412 100 3 1
6 3423 50 1 1
7 3434 100 1 1
8 3436 100 3 1
9 3438 50 3 1
10 3445 50 1 1
11 3454 100 3 1
12 3465 100 1 1
并且我想根据组从列 c 值 = 3 开始并且如果列 d 值在第一个组条目之前 + 30 则组结束的条件按列 a 和 b 进行分组(所以间隔长度= 30,但每个区间的起点可以在另一个区间)。然后我想统计每组的行数。
所以这个样本的预期输出应该是:
b a rowcount
100 -1 2 ( starting at d = 3400)
50 1 3 ( starting at d = 3400)
100 1 3 (starting at d= 3412)
50 1 2 (starting at d= 3438)
100 1 2 (starting at d= 3454)
我试过了:
df<-df%>%
group_by(b,a,first(c) == 3 & lead(d) - d < 30)
summarise(number = n())
但这并没有给我想要的输出。任何 cmet 都表示赞赏!
更新:新示例:
d b c a
1 3400 100 3 1
2 3400 100 3 1
3 3400 100 1 1
4 3408 100 1 1
5 3412 100 3 1
6 3434 100 3 1
7 3436 100 1 1
8 3438 100 3 1
9 3445 100 1 1
10 3443 100 3 1
11 3444 100 1 1
12 3463 100 3 1
13 3463 100 1 1
14 3463 100 3 1
您的代码作为输出给出:
a b count desc addition_info
<dbl> <dbl> <int> <chr> <chr>
1 1 100 5 ( starting at d = 3400) There is 3 `c == 3` in this group
2 1 100 6 ( starting at d = 3434) There is 3 `c == 3` in this group
3 1 100 3 ( starting at d = 3463) There is 2 `c == 3` in this group
但是第三组是错误的,因为 d = 29 的差异,因此
a b count desc addition_info
<dbl> <dbl> <int> <chr> <chr>
1 1 100 5 ( starting at d = 3400) There is 3 `c == 3` in this group
2 1 100 9 ( starting at d = 3434) There is 3 `c == 3` in this group
【问题讨论】:
-
从第 1 行开始,c == 3 所以我开始了一个小组。查看具有相同 b (100) 但 d
-
因为前两行 b(100) 行(第 1 行和第 3 行)的 a == -1 列和第 5 行的 a ==1 列,所以这将启动一个新组跨度>
-
对于最后一个
a =1; b = 100和starting at d = 3454第二条记录有d = 3645所以 d 差异大于30并且仍然在同一组中? -
很抱歉这是我的错误,我已更正。感谢您的解决方案,是否有可能包含 d
-
如果有
c == 1和d > 30的记录(或几条)那么会发生什么。它(或他们)会是它自己的组还是将包含在下一个c == 3中?那些c != 3之后会发生什么
标签: r dplyr group-by conditional-statements