You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言实现可指定产品、时间周期的客户还款Top10统计功能

需求说明

用户可指定产品(如Gold)和统计时间周期(按年或按月),函数需自动接收上述输入参数完成对应统计。

初始问题代码

原代码未实现参数匹配逻辑,仅固定按年+月+产品+客户分组取Top10还款金额记录,未接入入参的产品筛选、周期控制逻辑:

func_cust<-function(res) {
   res <-
      cust_repay%>%
      group_by(Customer,
               Year=lubridate::year(Month),
               Month=lubridate::month(Month),
               Product) %>%
      summarise(tot_amt = sum(Amount))%>%
      arrange(desc(tot_amt))%>%
      filter(row_number()<= 10)
   print(res)
}

View(func_cust("Gold"))
调整后可实现需求的代码

修改后函数新增两个入参:product为指定产品名称,period可选值为"year"/"month",默认按年统计:

library(dplyr)
library(lubridate)

func_cust <- function(product, period = "year") {
  # 产品维度筛选
  filter_df <- cust_repay %>%
    filter(Product == product)
  
  # 按指定统计周期配置分组字段
  group_cols <- c("Customer", "Product")
  if (period %in% c("year", "month")) {
    group_cols <- c(group_cols, "Year")
  }
  if (period == "month") {
    group_cols <- c(group_cols, "Month")
  }
  
  # 统计取Top10逻辑
  res <- filter_df %>%
    mutate(Year = year(Month),
           Month = month(Month)) %>%
    group_by(across(all_of(group_cols))) %>%
    summarise(tot_amt = sum(Amount), .groups = "drop") %>%
    arrange(desc(tot_amt)) %>%
    slice_head(n = 10)
  
  return(res)
}

# 调用示例1:统计Gold产品按年的Top10客户还款金额
View(func_cust(product = "Gold", period = "year"))
# 调用示例2:统计Silver产品按月的Top10客户还款金额
View(func_cust(product = "Silver", period = "month"))

内容的提问来源于stack exchange,提问作者Arnab S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:57:02