嗨,
我想通过mccmnc的前三位过滤每个客户的最大日期时间值。
如图所示,customer == 'abghsd'
具有两个不同的mccmnc值'53208'和'53210'。但是, mccmnc的前三位数是相同的(532)。因此,我想用mccmnc = '532'
来过滤客户abghsd的最大日期时间值。对于customer = 'abbaedl'
,我需要过滤mccmnc = '623'
和mccmnc = '451'
的最大日期时间。
那么我可以问一下如何为这个问题提供条件吗?
通过下面的查询,我可以按datetime
和customer
过滤mccmnc
,但是我想过滤mccmnc的前三位数字。
processed <- aggregate(datetime ~ customer + mccmnc, data =raw_data3, max)
这是我想要得到的结果:
Customer datetime mccmnc
abghsd 20181123222022 53210
abbaedl 20181226121213 62330
abbaedl 20181227191919 45123
谢谢。
答案 0 :(得分:1)
编辑原始代码,只需添加substr()
:
processed <- aggregate(datetime ~ customer + substr(mccmnc, 1, 3), data = raw_data3, max)
或者,使用tidyverse
解决方案:
library(tidyverse)
df %>%
# Group by customer ID and first 3 characters of mccmnc
group_by(customer, mccmnc_group = substr(mccmnc, 1, 3)) %>%
# Get the max datetime per group
summarise(max_datetime = max(datetime)) %>%
# Put columns in original order
select(1, 3, 2)
# A tibble: 3 x 3
# Groups: customer [2]
customer max_datetime mccmnc_group
<fct> <dbl> <chr>
1 John Package 20181201 532
2 Miranda Nuts 20181227 451
3 Miranda Nuts 20181226 623
df <- data.frame(customer = c(rep("John Package", 3), rep("Miranda Nuts", 4)),
datetime = c(20181123, 20181201, 20181124, 20181125, 20181226, 20181226, 20181227),
mccmnc = c("532-08", "532-08", "532-10", "623-12", "623-30", "451-21", "451-23"))
> df
customer datetime mccmnc
1 John Package 20181123 532-08
2 John Package 20181201 532-08
3 John Package 20181124 532-10
4 Miranda Nuts 20181125 623-12
5 Miranda Nuts 20181226 623-30
6 Miranda Nuts 20181226 451-21
7 Miranda Nuts 20181227 451-23