如何在R中按客户维度横向合并月度支付数据?
用R按客户维度整合月度支付数据
需求说明
将长格式的客户月度支付记录,转换为每个客户唯一一行、每月支付金额作为单独列的宽格式数据,每行对应一个客户,列包含客户ID及各月份的支付金额。
示例数据
df <- read.table(text=" Customer Payment Snapshot 10001 20000 31-Jan-00 10001 19000 29-Feb-00 10001 18000 31-Mar-00 10001 17000 30-Apr-00 10001 16000 31-May-00 10001 15000 30-Jun-00 10001 14000 31-Jul-00 10001 13000 31-Aug-00 10001 12000 30-Sep-00 10001 11000 31-Oct-00 10001 10000 30-Nov-00 10001 9000 31-Dec-00 10002 50000 31-Jan-00 10002 48500 29-Feb-00 10002 47000 31-Mar-00 10002 45500 30-Apr-00 10002 44000 31-May-00 10002 42500 30-Jun-00 10002 41000 31-Jul-00 10002 39500 31-Aug-00 10002 38000 30-Sep-00 10002 36500 31-Oct-00 10002 35000 30-Nov-00 10002 33500 31-Dec-00", header=T)
解决方案
推荐两种常用的长转宽方法,均能实现需求:
方法1:使用tidyverse工具链
- 若未安装依赖包,先执行
install.packages(c("dplyr", "tidyr")) - 转换日期格式并提取月份标识,再转宽格式
# 加载包 library(dplyr) library(tidyr) # 处理数据并转宽 df_wide <- df %>% mutate(Snapshot = as.Date(Snapshot, format = "%d-%b-%y")) %>% mutate(Month = format(Snapshot, "%b-%y")) %>% pivot_wider(names_from = Month, values_from = Payment) # 查看结果 print(df_wide)
方法2:使用reshape2包的dcast函数
- 未安装包先执行
install.packages("reshape2") - 处理日期后直接转宽
library(reshape2) # 提取月份标识 df$Month <- format(as.Date(df$Snapshot, "%d-%b-%y"), "%b-%y") # 转宽格式 df_wide2 <- dcast(df, Customer ~ Month, value.var = "Payment") # 查看结果 print(df_wide2)
结果说明
转换后的数据以Customer为唯一行标识,每一列对应一个月份的支付金额,完全匹配需求格式。
内容的提问来源于stack exchange,提问作者Yhan
相关产品推荐
相关产品推荐

