You need to enable JavaScript to run this app. R语言如何从regular_season中筛选championships对应id的子集
优惠活动
大模型
产品
解决方案
定价
更多

R语言如何从regular_season中筛选championships对应id的子集

R代码优化方案

原代码问题排查

  • 逻辑冗余:通过两次setdiff取交集的操作完全没有必要,增加不必要的计算量
  • 核心错误:第三行代码id_champ_in_rs <- numeric(length(champ_in_rs))生成了和目标id长度一致的全0数值向量,没有使用实际的匹配id值,最终筛选时匹配全0向量自然返回空数据集,数据量较大时异常索引逻辑可能导致R崩溃。

优化代码方案

方案1:基础R极简实现(仅需1行代码)

直接通过%in%匹配共有id即可实现需求:

champ_in_rs <- subset(regular_season, user_id %in% championships$id)

对应你给出的示例,该代码会自动筛选出regular_season中user_id为6、35的所有记录,完全符合预期。

方案2:显式取交集后筛选(可读性更强)

如果需要先明确共有id再做筛选,可以用intersect函数:

# 提取两个数据集的共有用户id
common_user_ids <- intersect(regular_season$user_id, championships$id)
# 筛选常规赛中对应id的记录
champ_in_rs <- subset(regular_season, user_id %in% common_user_ids)

方案3:tidyverse风格实现

如果你常用dplyr处理数据,可以用semi_join(专门用于提取左表中在右表有匹配项的记录):

library(dplyr)
champ_in_rs <- regular_season %>%
  semi_join(championships, by = c("user_id" = "id"))

内容的提问来源于stack exchange,提问作者Aaron

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 05:45:03