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

使用R识别数据框中首次满足条件的变化并忽略后续变动

R语言标记首次满足指定条件的位置并忽略后续变化

需求说明

我们需要在数据框中,标记**首次出现response == 0**的位置为"yes",其余位置均为"no",后续再出现符合条件的值也不再标记。

示例数据

df <- data.frame(response = c(1, 1, 1, 0, 1, 0))

实现方法

方法1:Base R 原生实现

先定位首次满足条件的索引,再批量赋值:

# 找到首次出现0的行索引
first_match <- which(df$response == 0)[1]
# 初始化Threshold列为"no",再修改目标位置为"yes"
df$Threshold <- "no"
df$Threshold[first_match] <- "yes"

方法2:dplyr 管道式实现

适合处理大型数据集或需要链式操作的场景:

library(dplyr)

df <- df %>%
  mutate(Threshold = case_when(
    row_number() == which(response == 0)[1] ~ "yes",
    TRUE ~ "no"
  ))

验证结果

最终生成的数据框与期望输出完全一致:

f <- data.frame(response = c(1, 1, 1, 0, 1, 0), Threshold = c("no", "no", "no", "yes", "no", "no"))
all.equal(df, f) # 输出 TRUE,说明结果匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:40:33