r - 根据另一个属性计算日期列中的更改次数
问题描述
大家好,我在数据验证过程中遇到了问题。我需要为名称列中的每个唯一变量在日期列中更改的次数。例如:
student.data <- data.frame(student_id = c (1:7),
student_name=c("Rick","Rick","Michelle","Michelle","Rick","Michelle","John"),
mark = c(623.3,515.2,611.0,729.0,843.25,459.4,846.65),
date_of_exam = as.Date(c("2014-01-01","2013-09-23","2014-11-15","2014-05-11", "2014-01-01","2016-04-14","2015-05-12")))
我知道它有点复杂,但结果必须是:
>table
>"Rick"
1
>"Michelle"
2
>"John"
0
在此先感谢您的帮助。
解决方案
您可以按学生分组并计算不同日期的数量并减去一个:
library(dplyr)
student.data %>%
group_by(student_name) %>%
summarise(cnt = n_distinct(date_of_exam) -1)
# A tibble: 3 x 2
student_name cnt
<fct> <dbl>
1 John 0
2 Michelle 2
3 Rick 1
推荐阅读
- kubernetes - 如何检查 Helm 图表/k8s 模板中是否存在 k8s 机密,或使用默认值?
- javascript - 与相同的字符串相比,Object.keys 中的“Key”不返回 true
- .net - 将 url 路径重写为 API 的子域
- python - 在 mpi4py 窗口上使用活动目标同步 Start() Complete() Post() Wait() 的正确方法是什么?
- python - 填写 html 问卷时为用户分配一个数字
- java - NullPointerException 构建二叉搜索树
- javascript - 捆绑后 SVG 图标不呈现(webpack)
- c# - 在使用 Azure 服务总线消息后尝试连接到我的数据库时处理上下文实例错误
- javascript - 如何有效地更改在 JS/TS 中具有递归的对象中某个键的值
- r - R 栅格函数将不接受 WKT 格式的 crs