通过改变因子值的R标签序列

发布于 2025-01-13 06:06:25 字数 2417 浏览 0 评论 0原文

我有以下数据:

帐户日期类型
12021-08-310
12021-09-230
12021-09-305
12021-10-300
12021-12-290
12022-01-318
12022-02-020

我需要找到每个单独转换的最短日期。

group_by(Account, type) %>%
summarise(first_appearance = min(date))

返回

帐户日期类型
12021-08-310
12021-09-305
12022-01-318

如何按类型中的每个 SHIFT 进行分组?

我最初的想法是沿着因子生成某种序列并连接起来以获得唯一的分组变量,但是这是如何完成的呢?

账户日期类型订单type_order
12021-08-310A0A
12021-09-230A0A
12021-09-305A5A
12021-10-300B0B
12021-12-290B0B
12022-01-318A8A
12022-02-020C0C

所需的输出为:

group_by(Account, type_order) %>%
summarise(first_appearance = min(date))
Accountdatetypeordertype_order
12021-08-310A0A
12021-09-305A5A
12021-10-300B0B
12022 -01-318A8A
12022年2月2日00 ℃

I have the following data:

Accountdatetype
12021-08-310
12021-09-230
12021-09-305
12021-10-300
12021-12-290
12022-01-318
12022-02-020

I need to find the minimum date of each individual transition.

group_by(Account, type) %>%
summarise(first_appearance = min(date))

returns

Accountdatetype
12021-08-310
12021-09-305
12022-01-318

How can I group by each SHIFT in type?

My initial thoughts are to generate some sort of sequence along the factors and concatenate to have a unique grouping variable, but how would this be done?

Accountdatetypeordertype_order
12021-08-310A0A
12021-09-230A0A
12021-09-305A5A
12021-10-300B0B
12021-12-290B0B
12022-01-318A8A
12022-02-020C0C

Desired output would be:

group_by(Account, type_order) %>%
summarise(first_appearance = min(date))
Accountdatetypeordertype_order
12021-08-310A0A
12021-09-305A5A
12021-10-300B0B
12022-01-318A8A
12022-02-020C0C

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

妳是的陽光 2025-01-20 06:06:25

当行与行之间的类型存在差异时,可以使用 data.table 中的 rleid 来分配组。

library(tidyverse)
library(data.table)

df %>%
  group_by(Account, grp = rleid(type), type, order) %>%
  summarise(first_appearance = min(date))

输出

  Account   grp  type order first_appearance
    <int> <int> <int> <chr> <chr>           
1       1     1     0 A     2021-08-31      
2       1     2     5 A     2021-09-30      
3       1     3     0 B     2021-10-30      
4       1     4     8 A     2022-01-31      
5       1     5     0 C     2022-02-02

Maybe use rleid from data.table to assign groups when there are differences in type from row to row.

library(tidyverse)
library(data.table)

df %>%
  group_by(Account, grp = rleid(type), type, order) %>%
  summarise(first_appearance = min(date))

Output

  Account   grp  type order first_appearance
    <int> <int> <int> <chr> <chr>           
1       1     1     0 A     2021-08-31      
2       1     2     5 A     2021-09-30      
3       1     3     0 B     2021-10-30      
4       1     4     8 A     2022-01-31      
5       1     5     0 C     2022-02-02
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文