首页 > 解决方案 > 评估错误:“n_distinct()”至少需要一列

问题描述

我正在使用 R 编程语言。我有一个包含 2 列的数据框(my_file):my_date(例如 2000-01-15,因子格式)和“blood_type”(也是因子格式)。我正在尝试使用 dplyr 库按组(按月)生成不同的计数。

我想出了如何进行非明确计数:

library(dplyr)

new_file <- my_file %>%
mutate(date = as.Date(my_date)) %>%
group_by(blood_type, month = format(date, "%Y-%m")) %>%
summarise(count = n())

但这不适用于不同的计数:

new_file <- my_file %>%
mutate(date = as.Date(my_date)) %>%
group_by(blood_type, month = format(date, "%Y-%m")) %>%
summarise(count = n_distinct())

Evaluation Error : Need at least one column for 'n_distinct()'

我试图显式引用该列,但这会产生一个空文件:

new_file <- my_file %>%
mutate(date = as.Date(my_date)) %>%
group_by(blood_type, month = format(date, "%Y-%m")) %>%
summarise(count = n_distinct(my_file$blood_type))

有人可以告诉我我做错了什么吗?

谢谢

标签: rdplyrgroup-bycountdistinct

解决方案


如果您想blood_type为每个月计算不同的,请不要将其包含在group_by. 尝试 :

library(dplyr)

new_file <- my_file %>%
  mutate(date = as.Date(my_date)) %>%
  group_by(month = format(date, "%Y-%m")) %>%
  summarise(count = n_distinct(blood_type))

推荐阅读