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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:33:17