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

如何在R语言中使用dplyr统计非缺失的唯一id行数

分组统计排除"none"的唯一id数量

先看原始数据和生成代码:

library(dplyr)
mydat <- data.frame(id = c(123, 111, 234, "none", 123, 384, "none"),
                    id2 = c(1, 1, 1, 2, 2, 3, 4))

数据输出:

id id2
1  123   1
2  111   1
3  234   1
4 none   2
5  123   2
6  384   3
7 none   4

需求:按id2分组,统计每组中**不含"none"**的唯一id数量。

原代码直接使用n_distinct(id)会把"none"也计入统计,导致结果不符合预期:

mydat %>% group_by(id2) %>% summarise(count = n_distinct(id))

错误输出:

# A tibble: 4 × 2
    id2 count
  <dbl> <int>
1     1     3
2     2     2
3     3     1
4     4     1

我们需要的正确输出是:

# A tibble: 4 × 2
    id2 count
  <dbl> <int>
1     1     3
2     2     1
3     3     1
4     4     0

解决方法

两种简洁的实现方式:

方法一:在n_distinct中直接过滤"none"

mydat %>% 
  group_by(id2) %>% 
  summarise(count = n_distinct(id[id != "none"]))

方法二:把"none"转为NA后统计(n_distinct默认忽略NA)

mydat %>%
  group_by(id2) %>%
  summarise(count = n_distinct(ifelse(id == "none", NA, id)), .groups = "drop")

两种方法都能得到预期结果,其中方法二更简洁,利用n_distinct忽略NA的特性自动排除"none",全是"none"的分组会直接返回0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:40:21