使用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
相关产品推荐
相关产品推荐

