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

如何在R中统计整数范围内所有整数的出现次数(未出现值补0)

解决方法

方法1:用factor()指定水平后统计

先把向量转换成包含目标整数范围所有值的因子,再用table()统计,就能让未出现的整数自动返回0计数。

示例代码:

my_vector <- c(4, 0, 3, 3, 6, 2, 4, 0)
# 定义需要统计的整数范围:0到6
target_range <- 0:6
# 将向量转为因子,强制设置水平为目标范围
my_factor <- factor(my_vector, levels = target_range)
# 统计次数
table(my_factor)

输出结果:

my_factor
0 1 2 3 4 5 6 
2 0 1 2 2 0 1 

方法2:tidyverse风格(dplyr+tidyr)

如果习惯用数据框格式处理,这个方法更灵活,方便后续分析:

library(dplyr)
library(tidyr)

my_vector <- c(4, 0, 3, 3, 6, 2, 4, 0)
target_range <- 0:6

tibble(value = my_vector) %>%
  count(value) %>%
  complete(value = target_range, fill = list(n = 0))

输出结果:

# A tibble: 7 × 2
  value     n
  <int> <dbl>
1     0     2
2     1     0
3     2     1
4     3     2
5     4     2
6     5     0
7     6     1

方法3:基础R的tabulate()函数

tabulate()专门统计正整数出现次数,只需稍微调整向量值适配它的计数规则:

my_vector <- c(4, 0, 3, 3, 6, 2, 4, 0)
target_range <- 0:6
# 把向量值加1,让0变成1(适配tabulate从1开始计数的规则)
adjusted_vec <- my_vector + 1
# 统计次数,length.out指定结果长度为目标范围的长度
counts <- tabulate(adjusted_vec, length.out = length(target_range))
# 给结果命名对应目标整数
names(counts) <- target_range
counts

输出结果:

0 1 2 3 4 5 6 
2 0 1 2 2 0 1 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:20:33