在R中按月-年统计不同观测值的数量
问题描述
我有如下简化后的data frame:
number opened_at YHGYA8A6Y8 07/11/2022 YHGYA8A6YA 07/11/2022 YHGYA842AZ 26/10/2022 YHGYA842AY 26/10/2022 YHGYA7Y4Z7 27/09/2022 YHGYA7Y4Z8 27/09/2022 YHGYA6Z284 31/08/2022 YHGYA6Z285 31/08/2022 YHGYA46Y23 29/07/2022 YHGYA46Y24 29/07/2022 YHGYA33443 29/06/2022 YHGYA33444 29/06/2022 YHGYA2Z8Z7 31/05/2022 YHGYA2Z8Z8 31/05/2022 YHGYAZ57YA 27/04/2022 YHGYAZ572Z 27/04/2022 YHGY8A326A 29/03/2022 YHGY8A327Z 29/03/2022 YHGY875723 20/02/2022 YHGY875724 20/02/2022 YHGY865563 28/01/2022 YHGY865564 28/01/2022
希望在R中创建一个表格,统计每个"Month-Year"对应的观测值数量,已知Excel数据透视表可以实现,但暂未找到R中的解决方案。
解决方案
方法一:基础R实现
- 先将
opened_at列转换为日期格式(原数据是日/月/年结构,需指定格式参数):
# 假设数据框名为df df$opened_at <- as.Date(df$opened_at, format = "%d/%m/%Y")
- 提取
Month-Year格式的日期字符串:
df$month_year <- format(df$opened_at, "%m-%Y")
- 用
table()函数统计分组数量,也可转为数据框格式方便查看:
count_table <- table(df$month_year) # 转为数据框 count_df <- as.data.frame(count_table) colnames(count_df) <- c("Month-Year", "Count")
方法二:tidyverse工具包实现(更简洁)
先安装并加载tidyverse:
install.packages("tidyverse") library(tidyverse)
通过管道流一步完成日期转换、分组和计数:
count_df <- df %>% mutate(opened_at = dmy(opened_at), # dmy()自动识别日/月/年格式 month_year = format(opened_at, "%b-%Y")) %>% # %b为月份缩写(如Nov-2022),也可改用%m-%Y count(month_year, name = "Count") %>% arrange(desc(opened_at)) # 可选:按日期降序排列结果
注:dmy()来自lubridate包(已包含在tidyverse中),无需单独加载;count()函数直接完成分组计数,比group_by()+summarise()更简洁。
内容的提问来源于stack exchange,提问作者Marcelo Bastos
相关产品推荐
相关产品推荐

