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

R语言中当ID列存在重复值时如何替换Grade列不同值为NA

实现逻辑

按ID列分组后统计每组内Grade的唯一值数量,若数量大于1,说明同一ID对应多个不同的Grade,此时将该组所有Grade替换为NA即可。

方法1:tidyverse(dplyr)实现

library(dplyr)

# 构造示例数据,可替换为你自己的数据集
df <- data.frame(
  ID = c(1001, 1002, 1002, 1003),
  Name = c("Mary", "John", "John", "James"),
  Grade = c(10, 9, 10, 12)
)

# 核心处理逻辑
df_result <- df %>%
  group_by(ID) %>%
  mutate(Grade = ifelse(n_distinct(Grade) > 1, NA_real_, Grade)) %>%
  ungroup()

如果你的Grade列是整数类型,可将NA_real_替换为NA_integer_避免类型转换。

方法2:base R实现(无需加载第三方包)

# 构造示例数据,可替换为你自己的数据集
df <- data.frame(
  ID = c(1001, 1002, 1002, 1003),
  Name = c("Mary", "John", "John", "James"),
  Grade = c(10, 9, 10, 12)
)

# 统计每个ID对应Grade的唯一值数量
grade_unique_cnt <- ave(df$Grade, df$ID, FUN = function(x) length(unique(x)))
# 替换符合条件的Grade为NA
df$Grade[grade_unique_cnt > 1] <- NA

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:45:07