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

如何使用R将数据框指定列中的重复值替换为NA

R代码实现方案

以下两种方案都可以实现你要的效果:

方法1:使用dplyr包(写法简洁易读)

# 加载依赖包,没安装的话先运行 install.packages("dplyr")
library(dplyr)

# 构造原始数据
df <- structure(list(id = c(1, 1, 1, 2, 2, 2, 3, 3), time = c(412, 
412, 412, 121, 121, 121, 250, 250)), class = "data.frame", row.names = c(NA, 
-8L))

# 按id分组,仅保留每组第一行的time值,其余替换为NA
df <- df %>%
  group_by(id) %>%
  mutate(time2 = ifelse(row_number() == 1, time, NA)) %>%
  ungroup()

如果不需要保留原time列,直接将mutate里的time2改为time即可覆盖原列。

方法2:基础R实现(无需安装第三方包)

# 构造原始数据
df <- structure(list(id = c(1, 1, 1, 2, 2, 2, 3, 3), time = c(412, 
412, 412, 121, 121, 121, 250, 250)), class = "data.frame", row.names = c(NA, 
-8L))

# 按id分组标记首位位置,生成新列
df$time2 <- ifelse(ave(rep(1, nrow(df)), df$id, FUN = cumsum) == 1, df$time, NA)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:30:05