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

R语言计算日期观测值占比及count函数调用报错求助

R语言食品设施检查数据日期维度统计解决方案

报错原因

你遇到的报错:

Error in UseMethod("count"): no applicable method for 'count' applied to an object of class "factor"

是因为dplyr包的count()函数仅支持数据框作为输入对象,你直接传入了从数据框中提取的DateRecent因子列向量,不属于该函数支持的输入类型。

功能实现代码

方法一:基础R实现(无需加载第三方包)

# 1. 统计每个DateRecent分类的观测数
date_counts <- table(FoodFacilityInspections$DateRecent)
# 2. 计算各分类观测数占总观测数的比例
date_proportion <- prop.table(date_counts) * 100

# ---------- 需求1:获取观测数最多的日期及占比 ----------
max_date <- names(which.max(date_counts))
max_count <- max(date_counts)
max_ratio <- round(max_count / nrow(FoodFacilityInspections) * 100, 2)
# 输出结果
cat("观测最多的日期:", max_date, "\n该日期观测数:", max_count, "\n占总观测比例:", max_ratio, "%\n")

# ---------- 需求2:获取所有DateRecent分类的观测占比 ----------
# 整合为数据框查看
all_date_stat <- data.frame(
  日期 = names(date_counts),
  观测数 = as.numeric(date_counts),
  占比 = paste0(round(as.numeric(date_proportion), 2), "%")
)
# 查看完整统计结果
View(all_date_stat)

方法二:dplyr实现(管道语法更易读)

如果使用tidyverse生态工具,调整count()的入参即可:

library(dplyr)
# 一次性完成两个需求的统计
all_date_stat <- FoodFacilityInspections %>%
  # 按DateRecent列统计每组观测数
  count(DateRecent, name = "观测数") %>%
  # 计算占比,保留2位小数转百分比格式
  mutate(占比 = paste0(round(观测数 / sum(观测数) * 100, 2), "%")) %>%
  # 按观测数降序排序,第一行即为观测数最多的日期
  arrange(desc(观测数))

# 需求1结果:取第一行
max_date_stat <- slice_head(all_date_stat, n = 1)
print(max_date_stat)

# 需求2结果:直接查看全量统计
View(all_date_stat)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:45:02