【问题标题】:R Dplyr sub-settingR Dplyr 子设置
【发布时间】:2020-09-17 15:04:09
【问题描述】:

在对主要联系人的人口进行子设置后,我需要按客户计算 minmaxmean。为此,如果contact == relationamount < 25,我需要在客户组中删除观察结果。但是,棘手的部分是:如果contact == relationamount == amount,无论数量多少,我都需要保留这两个观察值(这说明了我们无法定义主要联系人的关系)。

如果contact == relation,可以认为这是一家之言。 每个客户可以由多个家庭组成,因此我已包含具有NULL 关系值的联系人。

样本数据

customer <- c(1,1,1,1,2,2,2,3,3,3,3)
contact <- c(1234,2345,3456,4567,5678,6789,7890,8901,9012,1236,2346)
relationship <- c(2345,1234,"","",6789,5678,"",9012,8901,2346,1236)
amount <- c(26,22,40,12,15,15,70,35,15,25,25)
score <- c(500,300,700,600,400,600,700,650,300,600,700)
creditinfoaggtestdata1 <- data.frame(customer,contact,relationship,amount,score)

预期结果

作为参考,如果我在计算 minmaxmean 之前没有删除适当的联系人,我会得到如下输出表:

【问题讨论】:

  • 第一段第二句,amount == amount是什么意思?
  • 很好的问题,如果您查看联系人 5678 和 6789 的金额 = 15 被认为是平局,两个联系人都不是主要联系人,联系人 5678 有关系 6789,而联系人 6789 有关系 5678 - 他们在同一个家庭像夫妻关系

标签: r data-manipulation


【解决方案1】:

我假设要求“联系人 = 关系和金额 = 金额”是指同一客户组内的不同行。这是dplyr 解决方案:

# Create a contact-relationship id where direction doesn't matter
df <- creditinfoaggtestdata1 %>% 
  rowwise() %>% 
  mutate(id = paste0(min(contact, relationship), max(contact, relationship))) 

# Filter new ID's where duplicates in amounts exist per customer group
dups <- df %>% 
  group_by(customer, id, amount) %>% 
  summarise(count = n()) %>% 
  filter(count > 1) %>% 
  ungroup() %>% 
  select(customer, id)

# User inner join to only select contact-relationship combinations from above
a <- df %>% 
  filter(amount < 25) %>% 
  inner_join(dups, by=c("customer", "id"))

# Combine with >= 25 data
b <- df %>% 
  filter(amount >= 25)

c <- rbind(a, b)

c %>% 
  group_by(customer) %>% 
  summarise(min_score = min(score), max_score = max(score), avg_score = mean(score))

Output:
  customer min_score max_score avg_score
     <dbl>     <dbl>     <dbl>     <dbl>
1        1       500       700      600 
2        2       400       700      567.
3        3       600       700      650

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2020-07-23
    • 2020-09-16
    • 2023-04-06
    相关资源
    最近更新 更多