r - 评估错误:“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))
有人可以告诉我我做错了什么吗?
谢谢
解决方案
如果您想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))
推荐阅读
- android - 无法使用 rootBundle 在颤振测试中加载资产
- rust - 函数中的可变寿命 qs
- java - Java - 可以使用 return 语句退出程序吗?
- python - 如何删除机器人直接消息?
- javascript - SignalR Group 消息应用程序,创建组消息框导致刷新
- android - Xamarin.Forms Live Player - 由于 API 版本不支持的设备
- typescript - 打字稿类型的 redux-persist MigrationManifest?
- jquery - 如何在 html 模板中使用 contextPath
- webpack - 非相对导入 - Ionic - Webpack - Sourcemaps 在 Chrome 中的一个文件上偏离了几行
- android - 我无法将活动的数据(字符串)发送到活动中包含的片段