R语言如何按月份统计数据集频次及对应月份总索赔成本?
如何在R中按月同时统计数据集条目频次与对应月份总索赔额
问题背景
使用CASdatasets包的itamtplcost数据集时,需要基于Date列按月分组,同步计算两个指标:
- 当月索赔条目数(频次)
- 当月总索赔额(total claim size)
数据集加载代码如下:
install.packages("CASdatasets", repos = "http://dutangc.free.fr/pub/RRepos/", type="source") library(CASdatasets) data("itamtplcost") # 加载数据集 head(itamtplcost) names(itamtplcost) View(itamtplcost)
原有代码仅能统计月度频次,无法计算总索赔额:
itamtplcost$Date <- as.Date(itamtplcost$Date, format="%d/%m/%Y") tab <- table(cut(itamtplcost$Date, 'month')) monthly_aggre<-data.frame(Date=format(as.Date(names(tab)), '%m/%Y'), Frequency=as.vector(tab))
目标输出效果参考:
解决方案
table()函数仅支持计数统计,要同步计算多维度聚合值,直接用分组聚合逻辑即可,以下是两种常用实现:
方法1:基础R实现,无需安装额外包
# 统一转换日期格式 itamtplcost$Date <- as.Date(itamtplcost$Date, format="%d/%m/%Y") # 为每条数据打上月份分组标签 itamtplcost$month_group <- cut(itamtplcost$Date, breaks = "month") # 同步聚合频次与总索赔额 monthly_aggre <- aggregate( x = list( Frequency = itamtplcost$Date, TotalClaimSize = itamtplcost$`total claim size` ), by = list(month_group = itamtplcost$month_group), FUN = function(col) if(is.numeric(col)) sum(col, na.rm = TRUE) else length(col) ) # 转换为目标月/年显示格式 monthly_aggre$Date <- format(monthly_aggre$month_group, "%m/%Y") # 整理输出列顺序 monthly_aggre <- monthly_aggre[, c("Date", "Frequency", "TotalClaimSize")]
方法2:dplyr实现,代码更简洁
适合习惯tidyverse语法的场景,可读性更高:
# 未安装dplyr、lubridate时先运行安装命令 # install.packages("dplyr") # install.packages("lubridate") library(dplyr) library(lubridate) itamtplcost$Date <- as.Date(itamtplcost$Date, format="%d/%m/%Y") monthly_aggre <- itamtplcost %>% group_by(month_group = floor_date(Date, "month")) %>% summarise( Frequency = n(), TotalClaimSize = sum(`total claim size`, na.rm = TRUE), .groups = "drop" ) %>% mutate(Date = format(month_group, "%m/%Y")) %>% select(Date, Frequency, TotalClaimSize)
注意:数据集里的总索赔额列名带空格,引用时必须用反引号包裹,否则R会识别为语法错误。运行前可先通过
names(itamtplcost)确认列名是否匹配。
内容的提问来源于stack exchange,提问作者miss alhejaili
相关产品推荐
相关产品推荐

