如何在R语言数据框中过滤同时修读数学与代数类课程学生的数学记录?
解决方案
可以使用dplyr包的分组与条件过滤实现需求,核心逻辑是先判断每个学生是否同时修读了math和代数类课程(algebra/pre-algebra),再针对性过滤掉符合条件的math记录:
library(dplyr) student_courses_filtered <- student_courses %>% group_by(student_id) %>% mutate( has_math = "math" %in% class, has_algebra = any(class %in% c("algebra", "pre-algebra")) ) %>% filter(!(has_math & has_algebra & class == "math")) %>% select(-has_math, -has_algebra) %>% ungroup()
代码说明:
group_by(student_id):按学生ID分组,实现对单个学生的课程集合单独判断mutate(...):新增两个辅助标记列:has_math:标记该学生是否修读了math课程has_algebra:标记该学生是否修读了algebra或pre-algebra课程
filter(!(has_math & has_algebra & class == "math")):仅过滤掉同时满足修读math和代数类课程的那条math记录,其余所有记录均保留select(-has_math, -has_algebra):移除临时辅助列,还原目标数据结构ungroup():取消分组,回到普通数据框格式
运行后得到的student_courses_filtered即为你需要的结果。
内容的提问来源于stack exchange,提问作者Misha
相关产品推荐
相关产品推荐

